Ошибка main method not found

When you use the java command to run a Java application from the command line, e.g.,

java some.AppName arg1 arg2 ...

the command loads the class that you nominated and then looks for the entry point method called main. More specifically, it is looking for a method that is declared as follows:

package some;
public class AppName {
    ...
    public static void main(final String[] args) {
        // body of main method follows
        ...
    }
}

The specific requirements for the entry point method are:

  1. The method must be in the nominated class.
  2. The name of the method must be «main» with exactly that capitalization1.
  3. The method must be public.
  4. The method must be static 2.
  5. The method’s return type must be void.
  6. The method must have exactly one argument and argument’s type must be String[] 3.

(The argument may be declared using varargs syntax; e.g. String... args. See this question for more information. The String[] argument is used to pass the arguments from the command line, and is required even if your application takes no command-line arguments.)

If anyone of the above requirements is not satisfied, the java command will fail with some variant of the message:

Error: Main method not found in class MyClass, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Or, if you are running an extremely old version of Java:

java.lang.NoSuchMethodError: main
Exception in thread "main"

If you encounter this error, check that you have a main method and that it satisfies all of the six requirements listed above.


1 — One really obscure variation of this is when one or more of the characters in «main» is NOT a LATIN-1 character … but a Unicode character that looks like the corresponding LATIN-1 character when displayed.
2 — Here is an explanation of why the method is required to be static.
3 — String must be the standard java.lang.String class and not to a custom class named String that is hiding the standard class.

Особенности IDE, которыми не следует пользоваться. Теоретически несколько классов в одном файле использовать возможно, и некоторые IDE сразу же позволяют использовать этот функционал. Но не следует делать так: всегда выносите классы в отдельные файлы (если не вложенные, само собой):
У автора в настройках запуска проекта явно указано, где расположен метод main. В NetBeans не работаю (но это именно аргумент, например, -classpath «ваш_путьdelbin» del.BankAccountTest), в Eclipse выставляется так (и файл BankAccountTest.class уже есть в bin — смотрите ниже):
5f29c5af0bb6f600410196.jpeg

Как воспроизвести:

Изначально два файла, в каждом ко классу:

5f29bfbbd4c57670847569.jpeg

Компилируем, получаем в bin два файла классов BankAccount.class и BankAccountTest.class, запускаем.

5f29bfd92631a688046295.jpeg

Удаляем BankAccountTest.java, а код переносим в BankAccount.java. Компилируем, запускаем.

5f29c05405046652034667.jpeg

А теперь удалите BankAccountTest.class — и IDE не сможет сослаться на main из удаленного BankAccountTest.class, несмотря на то, что, как выше показано, код второго класса перенесли в BankAccount.java (т.е. восстановили «исходное» состояние) — IDE не воспринимает класс BankAccountTest для компиляции.

5f29c72a203e1421617831.jpeg

Solution 1

What you have currently is just a constructor named Main, what Java needs is a main method with exact signature as:

public static void main(String[] args)
  • public — so that it can be called from outside

  • static — so that no need to create an instance of your class

  • void — not going to return any value

  • args — an array for command line parameters that you can specify while running the program

This is the entry point for your application.

When your current code is being invoked, JVM is trying to locate main method, and since its not present in your code, it’s throwing the exception which you have received.

Since you have mentioned beginner in your post, its worth mentioning that Java is a case sensitive languagemain and Main are not same in Java.

See also: The getting started tutorial.

Solution 2

The correct signature of main is:

public static void main(String[] args) {
   new Main();
}

It’s even written in the error message you posted.

Remove the ; from the constructor:

public Main() {
    run();
}

Solution 3

You have to use main() method in your program.
From here the program execution starts.

like

public static void main(String args[])
{
  //This is the starting point of your program.
}

This method must appear within a class, but it can be any class.
In the Java language, when you execute a class with the Java interpreter, the runtime system starts by calling the class’s main() method. The main() method then calls all the other methods required to run your application.

The main() method accepts a single parameter: an array of Strings. This parameter is the mechanism through which the runtime system passes command line arguments to your application

Solution 4

It’s looking for a method with this signature:

public static void main(String[] args)

To run your code, the main method can look like this:

public static void main(String[] args)
{
    new Main();
}

Solution 5

main method should exist for your application to run. Java applications need it to know where to begin executing the program.

Put the method in a class of your choice, and then right click file and select ‘Run file`.

 public static void main(String[] args)
 {
     // your code here
 }

Comments

  • I’m learning Java for my course and I’ve hit a brick wall. I’ve been tasked with developing a simple command line program. To make things easier I was given the following sample code to modify so I wouldn’t have to start from scratch.

    package assignment;
    
    public class Main {
    private final static String[] mainMenuOpts = {"Students","Lecturers","Admin","Exit"};
    private final static String[] studentMenuOpts = {"Add Student","List all Students","Find a Student","Return to Main Menu"};
    private Menu mainMenu = new Menu("MAIN MENU",mainMenuOpts);
    private Menu studentMenu = new Menu("STUDENT MENU",studentMenuOpts);
    private DataStore data = new DataStore();
    private java.io.PrintStream out = System.out;
    private ReadKb reader = new ReadKb();
    /** Creates a new instance of Main */
    public Main() {
        run();
    }
    
    private void run(){
        int ret = mainMenu.display();
        while(true){
            switch(ret){
                case 1: students();break;
                case 2: lecturers(); break;
                case 3: admin(); break;
                case 4: exit(); break;
            }
            ret = mainMenu.display();
        }
    }
    private void students(){
        int ret = studentMenu.display();
        while(ret != 4){
            switch(ret){
                case 1: addStudent();break;
                case 2: listStudents(); break;
                case 3: findStudent(); break;
            }
            ret = studentMenu.display();
        }
    }
    private void lecturers(){
        out.println("nLecturers not yet implemented");
    }
    private void admin(){
        out.println("nAdmin not yet implemented");
    }
    //Student methods
    private void addStudent(){
        out.println("ntAdd New Student");
        //prompt for details
        //add student to the datastore
        //ask if they want to enter another student - 
        // if so call addStudent again
        //otherwise the method completes and the studentMenu will display again
    
    }
    private void listStudents(){
        out.println("ntStudent Listing");
        //list all students from the datastore
    }
    private void findStudent(){
        out.println("ntFind Student");
        out.print("Enter Search String: ");
        //reasd search text
        //use datastore method to get list of students that contain the search string
        //display matching students
    
    }
    // end Student methods
    private void exit() {
        data.save();  //call the datastore method that will save to file
        out.println("nnGoodbye :)");
        System.exit(0);
        }
    }
    

    I’m using NetBeans and when I try to run the project I get this error:

    Error: Main method not found in class assignment.Main, please define the main method as: public static void main(String[] args)
    

    I just want to get the program running so I can understand the code better. I understand the error, but have no idea where to implement the main method in this wall of text. I’ve been experimenting for hours, but obviously as a newbie I’m completely useless. Any help would be greatly appreciated.

    • So where is the «main» method? (Also, try searching first :-/)

    • I really don’t know what was up with the edits…

    • I did search. I understood what the error was saying. I added a main method, but had no idea how to invoke the run() method through it without getting some other errors. I only started learning a few days ago (literally) so it’s all new to me. Anyway, problem solved with Tudor’s help.

  • I get this error adding that: Exception in thread «main» java.lang.RuntimeException: Uncompilable source code — missing method body, or declare abstract at assignment.Main.<init>(Main.java:28) at assignment.Main.main(Main.java:24) Java Result: 1

  • @user1410613: Please edit the question with the code you have now.

  • @user1410613: See the edit to my answer.

  • It’s working now. Thanks mate.

  • @user1410613: Don’t forget to accept the answer if it solved your problem. :)

Recents

Related

Добрый день.

Столкнулся с не возможностью запуска в IDE без добавления метода main. Код не компилируется в IDE и не проходит валидации.
Error: Main method not found in class com.javarush.task.pro.task06.task0615.Earth, please define the main method as:
public static void main(String[] args)

Если метод добавить — код компилируется, но валидации по прежнему не проходит.
как правильно эту задачу запустить в IDE?

package com.javarush.task.pro.task06.task0615;

/*
Все что нужно знать о Земле
*/

public class Earth {
public static final String name = «Земля»;
public static final double square = 510_100_000;
public static final long population = 7_594_000_000L;
public static final long equatorLength = 40_075_696;

}

I’m learning Java for my course and I’ve hit a brick wall. I’ve been tasked with developing a simple command line program. To make things easier I was given the following sample code to modify so I wouldn’t have to start from scratch.

package assignment;

public class Main {
private final static String[] mainMenuOpts = {"Students","Lecturers","Admin","Exit"};
private final static String[] studentMenuOpts = {"Add Student","List all Students","Find a Student","Return to Main Menu"};
private Menu mainMenu = new Menu("MAIN MENU",mainMenuOpts);
private Menu studentMenu = new Menu("STUDENT MENU",studentMenuOpts);
private DataStore data = new DataStore();
private java.io.PrintStream out = System.out;
private ReadKb reader = new ReadKb();
/** Creates a new instance of Main */
public Main() {
    run();
}

private void run(){
    int ret = mainMenu.display();
    while(true){
        switch(ret){
            case 1: students();break;
            case 2: lecturers(); break;
            case 3: admin(); break;
            case 4: exit(); break;
        }
        ret = mainMenu.display();
    }
}
private void students(){
    int ret = studentMenu.display();
    while(ret != 4){
        switch(ret){
            case 1: addStudent();break;
            case 2: listStudents(); break;
            case 3: findStudent(); break;
        }
        ret = studentMenu.display();
    }
}
private void lecturers(){
    out.println("nLecturers not yet implemented");
}
private void admin(){
    out.println("nAdmin not yet implemented");
}
//Student methods
private void addStudent(){
    out.println("ntAdd New Student");
    //prompt for details
    //add student to the datastore
    //ask if they want to enter another student - 
    // if so call addStudent again
    //otherwise the method completes and the studentMenu will display again

}
private void listStudents(){
    out.println("ntStudent Listing");
    //list all students from the datastore
}
private void findStudent(){
    out.println("ntFind Student");
    out.print("Enter Search String: ");
    //reasd search text
    //use datastore method to get list of students that contain the search string
    //display matching students

}
// end Student methods
private void exit() {
    data.save();  //call the datastore method that will save to file
    out.println("nnGoodbye :)");
    System.exit(0);
    }
}

I’m using NetBeans and when I try to run the project I get this error:

Error: Main method not found in class assignment.Main, please define the main method as: public static void main(String[] args)

I just want to get the program running so I can understand the code better. I understand the error, but have no idea where to implement the main method in this wall of text. I’ve been experimenting for hours, but obviously as a newbie I’m completely useless. Any help would be greatly appreciated.

Понравилась статья? Поделить с друзьями:
  • Ошибка man tga edc 03779 10
  • Ошибка main inspection performed on time w211
  • Ошибка man tga edc 03063 01
  • Ошибка main bios checksum error
  • Ошибка man ffr 03281 10