-3

I was just re-reading my lecture scripts and trying out the code there. The problem is that the professor gave us only fragments of code and I really stuck on this one. I keep getting this error in Eclipse:

no main method

I still get the error even if I put public static void main(String[] args) in the code. What should I change in it?

The main idea of this program is to calculate a square or square root.

public class MeineKlasse {

    private String job;

    private String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
        System.out.println(job);
    }

    public double myMethode(double x) throws Exception {
        if (job.equals("quadrat")) 
            return x * x;
        if (job.equals("wurzel")) 
            return Math.sqrt(x);
        System.out.println(myMethode(x) + "=");
        throw new Exception("Fehler:Aufgabe nicht korrekt definiert"); 
    }
}
The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
Yoana
  • 75
  • 2
  • 12

3 Answers3

6

Every program needs entry point. The entry point to any java program is

public static void main(String[] args)

You have to implement this method. It will run the rest of your application.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

If you get error like no main method it means you had to put your main method in the incorrect place. Make sure also your curly brackets are closed and follow this structure

public static MeineKlasse {
    public static void main(String[] args) {
         //your code
         //...
         //...
         //...
    }
}
Andrew_Dublin
  • 745
  • 6
  • 22
-1

What AlexR said is correct. Every program needs a main method, which is what runs the program.

You can fix it with something like this:

public class MeineKlasse {

    private String job;

    public static void main(String[] args) { //main method
        MeineKlasse meineKlasse = new MeineKlasse();
        meineKlasse.setJob("quadrat");
        System.out.println(meineKlasse.myMethode(3.6));
    } //end main method

    private String getJob() {
        return job;
    }
    .
    .
    .
}

Another problem you have is in myMethode(double x).

public double myMethode(double x) throws Exception {
    if (job.equals("quadrat")) 
        return x * x;
    if (job.equals("wurzel")) 
        return Math.sqrt(x);
    System.out.println(myMethode(x) + "="); //this line
    throw new Exception("Fehler:Aufgabe nicht korrekt definiert"); 
}

On line 6, the method calls itself. When it calls itself, it repeats the method over again, including calling itself. Because it just called itself again, it will go through the code until it calls itself, etc. This results in a StackOverflowException, because the method would otherwise repeat itself forever. To fix this, you can just remove the line, as the program already prints the result in the main method.

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75