Меню

Selection does not contain a main type eclipse ошибка

I am trying to run some java files in a new project. So I make the project, put the files in it and I try to run the main file so my game starts.

I get an error that says selection does not contain a main type.

I have tried several ways to run it:

  • Some say to launch eclipse again, tried this a dozen times.
  • Somewhere else someone pointed to open a new project and make a build path to the old project.

Didn’t work either.

I am pretty sure it must work because I ran it a few hours ago at school. How do I get this working? Thank you in advance!

jww's user avatar

jww

94.9k88 gold badges395 silver badges860 bronze badges

asked Apr 25, 2013 at 21:38

user2321611's user avatar

6

Right click on the folder where you put your main class then click on Build Path —> Use as Source Folder.

Finally run your main file as java application. Hope this problem will be solved.

If the option ‘Use as Source Folder’ is not visible then inside the ‘Build Path’ select the option ‘Remove from Build Path’. This will allow ‘Use as Source Folder’ option to appear in the ‘Build Path’.

Community's user avatar

answered Apr 11, 2014 at 23:41

Rashid's user avatar

RashidRashid

9011 gold badge6 silver badges2 bronze badges

4

The other answers are all valid, however, if you are still having a problem you might not have your class inside the src folder in which case Eclipse may not see it as part of the project. This would also invoke the same error message you have seen.

answered Sep 20, 2013 at 2:11

zen's user avatar

zenzen

5911 gold badge4 silver badges5 bronze badges

1

I hope you are trying to run the main class in this way, see screenshot:
screenshot of Eclipse file context menu

If not, then try this way. If yes, then please make sure that your class you are trying to run has a main method, that is, the same method definition as below:

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

I hope this will help you.

MC Emperor's user avatar

MC Emperor

21.8k14 gold badges80 silver badges126 bronze badges

answered Apr 26, 2013 at 6:47

NoNaMe's user avatar

NoNaMeNoNaMe

5,91430 gold badges80 silver badges110 bronze badges

0

The entry point for Java programs is the method:

public static void main(String[] args) {
    //Code
}

If you do not have this, your program will not run.

answered Apr 25, 2013 at 22:02

I resolved this by adding a new source folder and putting my java file inside that folder. «source folder» is not just any folder i believe. its some special folder type for java/eclipse and can be added in eclipse by right-click on project -> properties -> Java buld path -> Source and add a folder

answered Apr 22, 2014 at 18:44

mishal153's user avatar

mishal153mishal153

1,4283 gold badges25 silver badges37 bronze badges

1

Few things to check out:

  1. Do you have a main package? do all of your classes are under this package?
  2. Do you use a main class with public static void main(String[] args)?
  3. Do you declare: package ; in your main class?
  4. You can always clean the project before running it. In Eclipse — Just go to Project -> clean then run the app again.

answered Mar 6, 2014 at 15:15

Eyal Sooliman's user avatar

I ran into the same problem. I fixed by right click on the package -> properties -> Java Build Path -> Add folder (select the folder your code reside in).

answered Sep 1, 2014 at 17:30

Yang Zhang's user avatar

1

I am running eclipse from Ubuntu. Had this same problem and was able run the program through terminal. So I just moved the existing public static void main(String[] args) { just below the class declaration (it got automatically formatted by eclipse) and the next launch was successful. Then moved the main method back to where it was before and it worked fine this time.

answered Dec 30, 2015 at 18:47

hipokito's user avatar

hipokitohipokito

3833 silver badges11 bronze badges

1

I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions:
Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked.
Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem

Conclusion:
Eclipse and/or the lombok plugin have/has a bug.

answered Jun 1, 2019 at 19:06

Øyvind Roth's user avatar

Øyvind RothØyvind Roth

2072 silver badges11 bronze badges

1

Looks too late to answer but might help someone,

Having same problem i solved it by following steps:::::

Select Main class in eclipse then click on Window in menu bar,

Window-->Show view-->Select Outline

Right click on main(String[]):void then Run As —> java Application

Image reference for Running Main method

By doing this you can run the main method directly. This worked for me

answered Mar 20, 2021 at 4:59

Zakir Hussain's user avatar

Right Click > Run AS > Run Configurations

In this screen if your «Main class» Text field is empty, then add the class name by clicking «Search» button on the right side of the text field and choose the class file. And then click «Run» button on the bottom of the configuration screen. That’s it

answered Mar 4, 2019 at 5:32

Yithirash's user avatar

YithirashYithirash

3573 gold badges6 silver badges18 bronze badges

You must place all your files (file.java) under the root folder SRC.

answered Feb 28, 2014 at 16:47

Dev M's user avatar

Dev MDev M

1,4933 gold badges28 silver badges48 bronze badges

Make sure the main in public static void main(String[] args) is lower case. For me it didn’t work when I had it with capital letter.

answered Sep 21, 2018 at 7:05

sander's user avatar

sandersander

1,2323 gold badges15 silver badges40 bronze badges

Put your Main Java class file in src/main/java folder and check if there is not any error in ‘Java Build Path’ by following right click on project and select Java Build Path->Source.

Lalji Dhameliya's user avatar

answered May 15, 2019 at 5:41

Rajiv Ranjan's user avatar

If you are working with a Maven project you have to understand the fact that directory layout is bit different. In this the package name must be src/main/java.

For this update your source folder by right click on project root folder -> properties -> java build path -> source tab. Here remove all other source folders as they might have been added in wrong manner. Now, select project /src/main/java as the source folder. Add and apply the changes. Now refresh your workspace using F5.

This should fix the issue of not recognizing a main type.

answered Aug 14, 2019 at 5:03

Abhishek Rathore's user avatar

0

I ran into the same issue and found that there was an extra pair of braces (curly brackets) enclosing public static void main(String args) { … }. This method should really be at the top scope in the class and should not be enclosed around braces. It seems that it is possible to end up with braces around this method when working in Eclipse. This could be just one way you can see this issue when working with Eclipse. Happy coding!

answered Apr 30, 2014 at 6:50

shivesh suman's user avatar

I had this happen repeatedly after adding images to a project in Eclipse and making them part of the build path. The solution was to right-click on the class containing the main method, and then choose Run As -> Java Application. It seems that when you add a file to the build path, Eclipse automatically assumes that file is where the main method is. By going through the Run As menu instead of just clicking the green Run As button, it allows you to specify the correct entry-point.

answered May 26, 2014 at 5:42

Keven M's user avatar

Keven MKeven M

95216 silver badges43 bronze badges

1

When you save your file, make sure it has the extension .java. If it does not, Eclipse won’t know to read it as a java file.

answered Sep 8, 2014 at 13:07

KC McLaughlin's user avatar

I had this issue because the tutorial code I was trying to run wasn’t in the correct package even though I had typed in the package name at the top of each class.

I right-clicked each class, Refactor and Move To and accepted the package name suggestion.

Then as usual, Run AsJava Application.

And it worked :)

answered Jun 29, 2020 at 19:21

likejudo's user avatar

likejudolikejudo

3,1946 gold badges47 silver badges101 bronze badges

You must check this as well, Go to Java build path -> config build path, check that JRE System Library [Java SE -version] is check marked, try running the code again. This fixed my issue.

answered Mar 2, 2021 at 16:26

Anshul Khatri's user avatar

In my case I was using ant to perform the build, and clearly had the class setup in the build.xml file:

<target name="jar">
  <jar destfile="ec-stats.jar" includes="bin/**,src/**">
    <manifest>
        <attribute name="Main-Class" value="my.package.MyStatistics" />
    </manifest>
  </jar>
</target> 

But it still kept giving me the same error, until I right-clicked on the folder in Eclipse and chose Build Path -> Use As Source Folder.

enter image description here

See also Error: Selection does not contain a main type

answered Oct 18, 2021 at 18:51

user8128167's user avatar

user8128167user8128167

6,6066 gold badges63 silver badges79 bronze badges

Solved the issue as following:

  1. Going in Properties of the Project
  • 1.1) Inside «Java Compiler»: chose the: «Compiler compliance level:» to a specific version of JDK (in my case I choosed 15)

  • 1.2) Inside «Java Build Path», in the tab «Libraries», at the Modulepath: change the «JRE System Library» to the same of the version you choosed at step 1.1 above (in my case I picked JDK 15)

  1. Run the java file that contains a main method

answered Oct 20, 2021 at 17:58

Lucas Favaro Borsatto's user avatar

This can be resolved in two steps if you are using Eclipse IDE.

👉 Step I: Right click on the project and click Maven > Choose Up-date Project

👉 Step II: Select the project the click Ok button

enter image description here

Hope this helps.✔

answered Mar 26, 2022 at 15:19

Syed Aaqib Hussain's user avatar

This error usually occurs because jdk is not selected for the project. I had the same problem and this worked for me.

Make sure that your class file is inside src folder then follow below steps

Step 1: Right click on project folder
Step 2: Build Path —> Configure Build Path
Step 3: Select «Java Build Path» from the left corner of the window
Step 4: Under «Order and Export» Tab
Step 5: Click on any of the jdk available check box to select it.
Step 6: Click on Apply and Close.

answered Oct 3, 2022 at 13:17

Pratik Chandra Tripathi's user avatar

I am trying to run some java files in a new project. So I make the project, put the files in it and I try to run the main file so my game starts.

I get an error that says selection does not contain a main type.

I have tried several ways to run it:

  • Some say to launch eclipse again, tried this a dozen times.
  • Somewhere else someone pointed to open a new project and make a build path to the old project.

Didn’t work either.

I am pretty sure it must work because I ran it a few hours ago at school. How do I get this working? Thank you in advance!

jww's user avatar

jww

94.9k88 gold badges395 silver badges860 bronze badges

asked Apr 25, 2013 at 21:38

user2321611's user avatar

6

Right click on the folder where you put your main class then click on Build Path —> Use as Source Folder.

Finally run your main file as java application. Hope this problem will be solved.

If the option ‘Use as Source Folder’ is not visible then inside the ‘Build Path’ select the option ‘Remove from Build Path’. This will allow ‘Use as Source Folder’ option to appear in the ‘Build Path’.

Community's user avatar

answered Apr 11, 2014 at 23:41

Rashid's user avatar

RashidRashid

9011 gold badge6 silver badges2 bronze badges

4

The other answers are all valid, however, if you are still having a problem you might not have your class inside the src folder in which case Eclipse may not see it as part of the project. This would also invoke the same error message you have seen.

answered Sep 20, 2013 at 2:11

zen's user avatar

zenzen

5911 gold badge4 silver badges5 bronze badges

1

I hope you are trying to run the main class in this way, see screenshot:
screenshot of Eclipse file context menu

If not, then try this way. If yes, then please make sure that your class you are trying to run has a main method, that is, the same method definition as below:

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

I hope this will help you.

MC Emperor's user avatar

MC Emperor

21.8k14 gold badges80 silver badges126 bronze badges

answered Apr 26, 2013 at 6:47

NoNaMe's user avatar

NoNaMeNoNaMe

5,91430 gold badges80 silver badges110 bronze badges

0

The entry point for Java programs is the method:

public static void main(String[] args) {
    //Code
}

If you do not have this, your program will not run.

answered Apr 25, 2013 at 22:02

I resolved this by adding a new source folder and putting my java file inside that folder. «source folder» is not just any folder i believe. its some special folder type for java/eclipse and can be added in eclipse by right-click on project -> properties -> Java buld path -> Source and add a folder

answered Apr 22, 2014 at 18:44

mishal153's user avatar

mishal153mishal153

1,4283 gold badges25 silver badges37 bronze badges

1

Few things to check out:

  1. Do you have a main package? do all of your classes are under this package?
  2. Do you use a main class with public static void main(String[] args)?
  3. Do you declare: package ; in your main class?
  4. You can always clean the project before running it. In Eclipse — Just go to Project -> clean then run the app again.

answered Mar 6, 2014 at 15:15

Eyal Sooliman's user avatar

I ran into the same problem. I fixed by right click on the package -> properties -> Java Build Path -> Add folder (select the folder your code reside in).

answered Sep 1, 2014 at 17:30

Yang Zhang's user avatar

1

I am running eclipse from Ubuntu. Had this same problem and was able run the program through terminal. So I just moved the existing public static void main(String[] args) { just below the class declaration (it got automatically formatted by eclipse) and the next launch was successful. Then moved the main method back to where it was before and it worked fine this time.

answered Dec 30, 2015 at 18:47

hipokito's user avatar

hipokitohipokito

3833 silver badges11 bronze badges

1

I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions:
Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked.
Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem

Conclusion:
Eclipse and/or the lombok plugin have/has a bug.

answered Jun 1, 2019 at 19:06

Øyvind Roth's user avatar

Øyvind RothØyvind Roth

2072 silver badges11 bronze badges

1

Looks too late to answer but might help someone,

Having same problem i solved it by following steps:::::

Select Main class in eclipse then click on Window in menu bar,

Window-->Show view-->Select Outline

Right click on main(String[]):void then Run As —> java Application

Image reference for Running Main method

By doing this you can run the main method directly. This worked for me

answered Mar 20, 2021 at 4:59

Zakir Hussain's user avatar

Right Click > Run AS > Run Configurations

In this screen if your «Main class» Text field is empty, then add the class name by clicking «Search» button on the right side of the text field and choose the class file. And then click «Run» button on the bottom of the configuration screen. That’s it

answered Mar 4, 2019 at 5:32

Yithirash's user avatar

YithirashYithirash

3573 gold badges6 silver badges18 bronze badges

You must place all your files (file.java) under the root folder SRC.

answered Feb 28, 2014 at 16:47

Dev M's user avatar

Dev MDev M

1,4933 gold badges28 silver badges48 bronze badges

Make sure the main in public static void main(String[] args) is lower case. For me it didn’t work when I had it with capital letter.

answered Sep 21, 2018 at 7:05

sander's user avatar

sandersander

1,2323 gold badges15 silver badges40 bronze badges

Put your Main Java class file in src/main/java folder and check if there is not any error in ‘Java Build Path’ by following right click on project and select Java Build Path->Source.

Lalji Dhameliya's user avatar

answered May 15, 2019 at 5:41

Rajiv Ranjan's user avatar

If you are working with a Maven project you have to understand the fact that directory layout is bit different. In this the package name must be src/main/java.

For this update your source folder by right click on project root folder -> properties -> java build path -> source tab. Here remove all other source folders as they might have been added in wrong manner. Now, select project /src/main/java as the source folder. Add and apply the changes. Now refresh your workspace using F5.

This should fix the issue of not recognizing a main type.

answered Aug 14, 2019 at 5:03

Abhishek Rathore's user avatar

0

I ran into the same issue and found that there was an extra pair of braces (curly brackets) enclosing public static void main(String args) { … }. This method should really be at the top scope in the class and should not be enclosed around braces. It seems that it is possible to end up with braces around this method when working in Eclipse. This could be just one way you can see this issue when working with Eclipse. Happy coding!

answered Apr 30, 2014 at 6:50

shivesh suman's user avatar

I had this happen repeatedly after adding images to a project in Eclipse and making them part of the build path. The solution was to right-click on the class containing the main method, and then choose Run As -> Java Application. It seems that when you add a file to the build path, Eclipse automatically assumes that file is where the main method is. By going through the Run As menu instead of just clicking the green Run As button, it allows you to specify the correct entry-point.

answered May 26, 2014 at 5:42

Keven M's user avatar

Keven MKeven M

95216 silver badges43 bronze badges

1

When you save your file, make sure it has the extension .java. If it does not, Eclipse won’t know to read it as a java file.

answered Sep 8, 2014 at 13:07

KC McLaughlin's user avatar

I had this issue because the tutorial code I was trying to run wasn’t in the correct package even though I had typed in the package name at the top of each class.

I right-clicked each class, Refactor and Move To and accepted the package name suggestion.

Then as usual, Run AsJava Application.

And it worked :)

answered Jun 29, 2020 at 19:21

likejudo's user avatar

likejudolikejudo

3,1946 gold badges47 silver badges101 bronze badges

You must check this as well, Go to Java build path -> config build path, check that JRE System Library [Java SE -version] is check marked, try running the code again. This fixed my issue.

answered Mar 2, 2021 at 16:26

Anshul Khatri's user avatar

In my case I was using ant to perform the build, and clearly had the class setup in the build.xml file:

<target name="jar">
  <jar destfile="ec-stats.jar" includes="bin/**,src/**">
    <manifest>
        <attribute name="Main-Class" value="my.package.MyStatistics" />
    </manifest>
  </jar>
</target> 

But it still kept giving me the same error, until I right-clicked on the folder in Eclipse and chose Build Path -> Use As Source Folder.

enter image description here

See also Error: Selection does not contain a main type

answered Oct 18, 2021 at 18:51

user8128167's user avatar

user8128167user8128167

6,6066 gold badges63 silver badges79 bronze badges

Solved the issue as following:

  1. Going in Properties of the Project
  • 1.1) Inside «Java Compiler»: chose the: «Compiler compliance level:» to a specific version of JDK (in my case I choosed 15)

  • 1.2) Inside «Java Build Path», in the tab «Libraries», at the Modulepath: change the «JRE System Library» to the same of the version you choosed at step 1.1 above (in my case I picked JDK 15)

  1. Run the java file that contains a main method

answered Oct 20, 2021 at 17:58

Lucas Favaro Borsatto's user avatar

This can be resolved in two steps if you are using Eclipse IDE.

👉 Step I: Right click on the project and click Maven > Choose Up-date Project

👉 Step II: Select the project the click Ok button

enter image description here

Hope this helps.✔

answered Mar 26, 2022 at 15:19

Syed Aaqib Hussain's user avatar

This error usually occurs because jdk is not selected for the project. I had the same problem and this worked for me.

Make sure that your class file is inside src folder then follow below steps

Step 1: Right click on project folder
Step 2: Build Path —> Configure Build Path
Step 3: Select «Java Build Path» from the left corner of the window
Step 4: Under «Order and Export» Tab
Step 5: Click on any of the jdk available check box to select it.
Step 6: Click on Apply and Close.

answered Oct 3, 2022 at 13:17

Pratik Chandra Tripathi's user avatar

I am trying to run some java files in a new project. So I make the project, put the files in it and I try to run the main file so my game starts.

I get an error that says selection does not contain a main type.

I have tried several ways to run it:

  • Some say to launch eclipse again, tried this a dozen times.
  • Somewhere else someone pointed to open a new project and make a build path to the old project.

Didn’t work either.

I am pretty sure it must work because I ran it a few hours ago at school. How do I get this working? Thank you in advance!

jww's user avatar

jww

94.9k88 gold badges395 silver badges860 bronze badges

asked Apr 25, 2013 at 21:38

user2321611's user avatar

6

Right click on the folder where you put your main class then click on Build Path —> Use as Source Folder.

Finally run your main file as java application. Hope this problem will be solved.

If the option ‘Use as Source Folder’ is not visible then inside the ‘Build Path’ select the option ‘Remove from Build Path’. This will allow ‘Use as Source Folder’ option to appear in the ‘Build Path’.

Community's user avatar

answered Apr 11, 2014 at 23:41

Rashid's user avatar

RashidRashid

9011 gold badge6 silver badges2 bronze badges

4

The other answers are all valid, however, if you are still having a problem you might not have your class inside the src folder in which case Eclipse may not see it as part of the project. This would also invoke the same error message you have seen.

answered Sep 20, 2013 at 2:11

zen's user avatar

zenzen

5911 gold badge4 silver badges5 bronze badges

1

I hope you are trying to run the main class in this way, see screenshot:
screenshot of Eclipse file context menu

If not, then try this way. If yes, then please make sure that your class you are trying to run has a main method, that is, the same method definition as below:

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

I hope this will help you.

MC Emperor's user avatar

MC Emperor

21.8k14 gold badges80 silver badges126 bronze badges

answered Apr 26, 2013 at 6:47

NoNaMe's user avatar

NoNaMeNoNaMe

5,91430 gold badges80 silver badges110 bronze badges

0

The entry point for Java programs is the method:

public static void main(String[] args) {
    //Code
}

If you do not have this, your program will not run.

answered Apr 25, 2013 at 22:02

I resolved this by adding a new source folder and putting my java file inside that folder. «source folder» is not just any folder i believe. its some special folder type for java/eclipse and can be added in eclipse by right-click on project -> properties -> Java buld path -> Source and add a folder

answered Apr 22, 2014 at 18:44

mishal153's user avatar

mishal153mishal153

1,4283 gold badges25 silver badges37 bronze badges

1

Few things to check out:

  1. Do you have a main package? do all of your classes are under this package?
  2. Do you use a main class with public static void main(String[] args)?
  3. Do you declare: package ; in your main class?
  4. You can always clean the project before running it. In Eclipse — Just go to Project -> clean then run the app again.

answered Mar 6, 2014 at 15:15

Eyal Sooliman's user avatar

I ran into the same problem. I fixed by right click on the package -> properties -> Java Build Path -> Add folder (select the folder your code reside in).

answered Sep 1, 2014 at 17:30

Yang Zhang's user avatar

1

I am running eclipse from Ubuntu. Had this same problem and was able run the program through terminal. So I just moved the existing public static void main(String[] args) { just below the class declaration (it got automatically formatted by eclipse) and the next launch was successful. Then moved the main method back to where it was before and it worked fine this time.

answered Dec 30, 2015 at 18:47

hipokito's user avatar

hipokitohipokito

3833 silver badges11 bronze badges

1

I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions:
Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked.
Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem

Conclusion:
Eclipse and/or the lombok plugin have/has a bug.

answered Jun 1, 2019 at 19:06

Øyvind Roth's user avatar

Øyvind RothØyvind Roth

2072 silver badges11 bronze badges

1

Looks too late to answer but might help someone,

Having same problem i solved it by following steps:::::

Select Main class in eclipse then click on Window in menu bar,

Window-->Show view-->Select Outline

Right click on main(String[]):void then Run As —> java Application

Image reference for Running Main method

By doing this you can run the main method directly. This worked for me

answered Mar 20, 2021 at 4:59

Zakir Hussain's user avatar

Right Click > Run AS > Run Configurations

In this screen if your «Main class» Text field is empty, then add the class name by clicking «Search» button on the right side of the text field and choose the class file. And then click «Run» button on the bottom of the configuration screen. That’s it

answered Mar 4, 2019 at 5:32

Yithirash's user avatar

YithirashYithirash

3573 gold badges6 silver badges18 bronze badges

You must place all your files (file.java) under the root folder SRC.

answered Feb 28, 2014 at 16:47

Dev M's user avatar

Dev MDev M

1,4933 gold badges28 silver badges48 bronze badges

Make sure the main in public static void main(String[] args) is lower case. For me it didn’t work when I had it with capital letter.

answered Sep 21, 2018 at 7:05

sander's user avatar

sandersander

1,2323 gold badges15 silver badges40 bronze badges

Put your Main Java class file in src/main/java folder and check if there is not any error in ‘Java Build Path’ by following right click on project and select Java Build Path->Source.

Lalji Dhameliya's user avatar

answered May 15, 2019 at 5:41

Rajiv Ranjan's user avatar

If you are working with a Maven project you have to understand the fact that directory layout is bit different. In this the package name must be src/main/java.

For this update your source folder by right click on project root folder -> properties -> java build path -> source tab. Here remove all other source folders as they might have been added in wrong manner. Now, select project /src/main/java as the source folder. Add and apply the changes. Now refresh your workspace using F5.

This should fix the issue of not recognizing a main type.

answered Aug 14, 2019 at 5:03

Abhishek Rathore's user avatar

0

I ran into the same issue and found that there was an extra pair of braces (curly brackets) enclosing public static void main(String args) { … }. This method should really be at the top scope in the class and should not be enclosed around braces. It seems that it is possible to end up with braces around this method when working in Eclipse. This could be just one way you can see this issue when working with Eclipse. Happy coding!

answered Apr 30, 2014 at 6:50

shivesh suman's user avatar

I had this happen repeatedly after adding images to a project in Eclipse and making them part of the build path. The solution was to right-click on the class containing the main method, and then choose Run As -> Java Application. It seems that when you add a file to the build path, Eclipse automatically assumes that file is where the main method is. By going through the Run As menu instead of just clicking the green Run As button, it allows you to specify the correct entry-point.

answered May 26, 2014 at 5:42

Keven M's user avatar

Keven MKeven M

95216 silver badges43 bronze badges

1

When you save your file, make sure it has the extension .java. If it does not, Eclipse won’t know to read it as a java file.

answered Sep 8, 2014 at 13:07

KC McLaughlin's user avatar

I had this issue because the tutorial code I was trying to run wasn’t in the correct package even though I had typed in the package name at the top of each class.

I right-clicked each class, Refactor and Move To and accepted the package name suggestion.

Then as usual, Run AsJava Application.

And it worked :)

answered Jun 29, 2020 at 19:21

likejudo's user avatar

likejudolikejudo

3,1946 gold badges47 silver badges101 bronze badges

You must check this as well, Go to Java build path -> config build path, check that JRE System Library [Java SE -version] is check marked, try running the code again. This fixed my issue.

answered Mar 2, 2021 at 16:26

Anshul Khatri's user avatar

In my case I was using ant to perform the build, and clearly had the class setup in the build.xml file:

<target name="jar">
  <jar destfile="ec-stats.jar" includes="bin/**,src/**">
    <manifest>
        <attribute name="Main-Class" value="my.package.MyStatistics" />
    </manifest>
  </jar>
</target> 

But it still kept giving me the same error, until I right-clicked on the folder in Eclipse and chose Build Path -> Use As Source Folder.

enter image description here

See also Error: Selection does not contain a main type

answered Oct 18, 2021 at 18:51

user8128167's user avatar

user8128167user8128167

6,6066 gold badges63 silver badges79 bronze badges

Solved the issue as following:

  1. Going in Properties of the Project
  • 1.1) Inside «Java Compiler»: chose the: «Compiler compliance level:» to a specific version of JDK (in my case I choosed 15)

  • 1.2) Inside «Java Build Path», in the tab «Libraries», at the Modulepath: change the «JRE System Library» to the same of the version you choosed at step 1.1 above (in my case I picked JDK 15)

  1. Run the java file that contains a main method

answered Oct 20, 2021 at 17:58

Lucas Favaro Borsatto's user avatar

This can be resolved in two steps if you are using Eclipse IDE.

👉 Step I: Right click on the project and click Maven > Choose Up-date Project

👉 Step II: Select the project the click Ok button

enter image description here

Hope this helps.✔

answered Mar 26, 2022 at 15:19

Syed Aaqib Hussain's user avatar

This error usually occurs because jdk is not selected for the project. I had the same problem and this worked for me.

Make sure that your class file is inside src folder then follow below steps

Step 1: Right click on project folder
Step 2: Build Path —> Configure Build Path
Step 3: Select «Java Build Path» from the left corner of the window
Step 4: Under «Order and Export» Tab
Step 5: Click on any of the jdk available check box to select it.
Step 6: Click on Apply and Close.

answered Oct 3, 2022 at 13:17

Pratik Chandra Tripathi's user avatar

score:28

Accepted answer

I hope you are trying to run the main class in this way, see screenshot:
screenshot of Eclipse file context menu

If not, then try this way. If yes, then please make sure that your class you are trying to run has a main method, that is, the same method definition as below:

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

I hope this will help you.

score:0

I ran into the same issue and found that there was an extra pair of braces (curly brackets) enclosing public static void main(String args) { … }. This method should really be at the top scope in the class and should not be enclosed around braces. It seems that it is possible to end up with braces around this method when working in Eclipse. This could be just one way you can see this issue when working with Eclipse. Happy coding!

score:0

I had this happen repeatedly after adding images to a project in Eclipse and making them part of the build path. The solution was to right-click on the class containing the main method, and then choose Run As -> Java Application. It seems that when you add a file to the build path, Eclipse automatically assumes that file is where the main method is. By going through the Run As menu instead of just clicking the green Run As button, it allows you to specify the correct entry-point.

score:0

When you save your file, make sure it has the extension .java. If it does not, Eclipse won’t know to read it as a java file.

score:0

I had this issue because the tutorial code I was trying to run wasn’t in the correct package even though I had typed in the package name at the top of each class.

I right-clicked each class, Refactor and Move To and accepted the package name suggestion.

Then as usual, Run AsJava Application.

And it worked :)

score:0

You must check this as well, Go to Java build path -> config build path, check that JRE System Library [Java SE -version] is check marked, try running the code again. This fixed my issue.

score:0

In my case I was using ant to perform the build, and clearly had the class setup in the build.xml file:

<target name="jar">
  <jar destfile="ec-stats.jar" includes="bin/**,src/**">
    <manifest>
        <attribute name="Main-Class" value="my.package.MyStatistics" />
    </manifest>
  </jar>
</target> 

But it still kept giving me the same error, until I right-clicked on the folder in Eclipse and chose Build Path -> Use As Source Folder.

enter image description here

See also Error: Selection does not contain a main type

score:0

Solved the issue as following:

  1. Going in Properties of the Project
  • 1.1) Inside «Java Compiler»: chose the: «Compiler compliance level:» to a specific version of JDK (in my case I choosed 15)

  • 1.2) Inside «Java Build Path», in the tab «Libraries», at the Modulepath: change the «JRE System Library» to the same of the version you choosed at step 1.1 above (in my case I picked JDK 15)

  1. Run the java file that contains a main method

score:0

This can be resolved in two steps if you are using Eclipse IDE.

👉 Step I: Right click on the project and click Maven > Choose Up-date Project

👉 Step II: Select the project the click Ok button

enter image description here

Hope this helps.✔

score:1

You must place all your files (file.java) under the root folder SRC.

score:1

Make sure the main in public static void main(String[] args) is lower case. For me it didn’t work when I had it with capital letter.

score:1

Put your Main Java class file in src/main/java folder and check if there is not any error in ‘Java Build Path’ by following right click on project and select Java Build Path->Source.

score:1

If you are working with a Maven project you have to understand the fact that directory layout is bit different. In this the package name must be src/main/java.

For this update your source folder by right click on project root folder -> properties -> java build path -> source tab. Here remove all other source folders as they might have been added in wrong manner. Now, select project /src/main/java as the source folder. Add and apply the changes. Now refresh your workspace using F5.

This should fix the issue of not recognizing a main type.

score:2

Right Click > Run AS > Run Configurations

In this screen if your «Main class» Text field is empty, then add the class name by clicking «Search» button on the right side of the text field and choose the class file. And then click «Run» button on the bottom of the configuration screen. That’s it

score:3

Few things to check out:

  1. Do you have a main package? do all of your classes are under this package?
  2. Do you use a main class with public static void main(String[] args)?
  3. Do you declare: package ; in your main class?
  4. You can always clean the project before running it. In Eclipse — Just go to Project -> clean then run the app again.

score:3

I ran into the same problem. I fixed by right click on the package -> properties -> Java Build Path -> Add folder (select the folder your code reside in).

score:3

I am running eclipse from Ubuntu. Had this same problem and was able run the program through terminal. So I just moved the existing public static void main(String[] args) { just below the class declaration (it got automatically formatted by eclipse) and the next launch was successful. Then moved the main method back to where it was before and it worked fine this time.

score:3

I had this problem in two projects. Maven and command line worked as expected for both. The problems were Eclipse specific. Two different solutions:
Project 1): Move the main method declaration to the top within the class, above all other declarations like fields and constructors. Crazy, but it worked.
Project 2): The solution for Project 1) did not remedy the problem. However, removing lombok imports and explicitly writing a getter method solved the problem

Conclusion:
Eclipse and/or the lombok plugin have/has a bug.

score:3

Looks too late to answer but might help someone,

Having same problem i solved it by following steps:::::

Select Main class in eclipse then click on Window in menu bar,

Window-->Show view-->Select Outline

Right click on main(String[]):void then Run As —> java Application

Image reference for Running Main method

By doing this you can run the main method directly. This worked for me

score:5

The entry point for Java programs is the method:

public static void main(String[] args) {
    //Code
}

If you do not have this, your program will not run.

score:5

I resolved this by adding a new source folder and putting my java file inside that folder. «source folder» is not just any folder i believe. its some special folder type for java/eclipse and can be added in eclipse by right-click on project -> properties -> Java buld path -> Source and add a folder

score:48

The other answers are all valid, however, if you are still having a problem you might not have your class inside the src folder in which case Eclipse may not see it as part of the project. This would also invoke the same error message you have seen.

score:87

Right click on the folder where you put your main class then click on Build Path —> Use as Source Folder.

Finally run your main file as java application. Hope this problem will be solved.

If the option ‘Use as Source Folder’ is not visible then inside the ‘Build Path’ select the option ‘Remove from Build Path’. This will allow ‘Use as Source Folder’ option to appear in the ‘Build Path’.

Related Query

  • Java launch error selection does not contain a main type
  • Error: Selection does not contain a main type
  • Selection does not contain a main type in maven-archetype-webapp
  • Eclipse | Selection does not contain a main type yet main is there
  • Eclipse — Java — Selection does not contain a main type — git clone
  • Trying to run corejava ManagerTest.java Error: Selection does not contain a main type in Eclipse
  • Editor does not contain a main type
  • Editor does not contain a main type in Eclipse
  • Editor does not contain main type
  • java — Editor does not contain a main type
  • Android: Editor does not contain a main type
  • Eclipse saying selection does not contain a main type?
  • Editor does not contain main type in Eclipse
  • «Selection does not contain a main Type» — Eclipse Run Error
  • AspectJ causing «Editor does not contain a main type» error
  • Eclipse Editor does not contain a main type
  • Eclipse error with archived java projects «editor does not contain main type»
  • Eclipse error when trying to run Java application — «Selection does not contain a main type» — But it does?
  • Eclipse: «selection does not contain a main type» error when main function exists
  • Editor does not contain a main type — messed up Build path config
  • Selector does not contain a main type eclipse
  • «Selection does not contain a main type» error when running JavaFX in eclipse.
  • Editor does not contain a main type in sample project
  • Android error «Selection does not contain a main type»
  • Eclipse error: «Editor does not contain a main type»
  • Conditional Breakpoint Error — Type does not implement selector max and signature
  • Eclipse error: ‘Selection does not contain a main type/an applet’
  • Type IQuery does not take parameters Error in org.eclipse.equinox.p2.query and org.eclipse.equinox.p2.metadata
  • Why do I get a «Selection does not contain a main type» message in Eclipse?
  • Not able to create executable jar for webdriver+TestNg project which does not contain main method in any class

More Query from same tag

  • ant clean and ant debug build failed
  • Eclipse v4.17 incompatible jvm — revert to v4.16
  • eclipse- Open Navigation Drawer WIth Swiping
  • Renaming sub package names in my Android project
  • How to attach back the Android emulator to ADB?
  • eclipse gives error on start up after adding sbteclipse plugin
  • Java element filter does not work in eclipse helios (3.6) sr1
  • Eclipse PDT — Lost content assist. OverlappingFileLockException
  • C++ hello world on Linux
  • How to remove messageLabel from tab order in JFace’s TitleAreaDialog
  • How to deploy a new WAR file in Tomcat
  • How to navigate in eclipse from method implementation to method definition in interface?
  • Nested onClick Listener
  • Splash Screen will not display
  • Help me understand Eclipse’s Java Build Path
  • Illegal modifier for parameter [frmStartupGame]; only final is permitted
  • Eclipse indentation issues
  • Is it possible to set a subpackage as the root of the source DISPLAY in Eclipse?
  • RobotFramework cannot import Java keyword library
  • Request resource is not found 404 error while running maven project on tomcat in eclipse
  • Eclipse IDE for Scala : symbol is missing from classpath
  • Eclipse incorrect variable names
  • Content Assist not working in Eclipse for Android
  • Eclipse | Using content assist on findViewById error
  • Plugins for Eclipse/PyDev
  • Parse .uml file with eclipse uml2
  • How to open a Part without duplicate?
  • BufferedReader not closed warning not disappearing
  • A solution for classpath is read-only in eclipse
  • Is it possible to run incremental/automated JUnit testing in Eclipse?

Ошибка: выделение не содержит основного типа

Я пытаюсь запустить некоторые файлы Java в новом проекте. Итак, я делаю проект, помещаю в него файлы и пытаюсь запустить основной файл, чтобы моя игра запустилась.

Я получаю сообщение об ошибке selection does not contain a main type.

Я пробовал несколько способов запуска:

  • Некоторые говорят, чтобы снова запустить eclipse, пробовал это с десяток раз.
  • Где-то еще кто-то указал, чтобы открыть новый проект и сделать путь сборки к старому проекту.

Тоже не сработало.

Я почти уверен, что это должно работать, потому что я запускал его несколько часов назад в школе. Как мне заставить это работать? Заранее спасибо!

Щелкните правой кнопкой мыши папку, в которую вы поместили свой основной класс, затем нажмите Build Path -> Use as Source Folder.

Наконец, запустите свой основной файл как java-приложение. Надеюсь, эта проблема будет решена.

Если параметр «Использовать как исходную папку» не отображается, в «Пути сборки» выберите параметр «Удалить из пути сборки». Это позволит параметру «Использовать как исходную папку» появиться в «Пути сборки».

Создан 15 фев.

Все остальные ответы действительны, однако, если у вас все еще есть проблема, у вас может не быть вашего класса в папке src, и в этом случае Eclipse может не видеть его как часть проекта. Это также вызовет то же сообщение об ошибке, которое вы видели.

Создан 20 сен.

Я надеюсь, вы пытаетесь запустить основной класс таким образом, см. скриншот:
скриншот контекстного меню файла Eclipse

Если нет, то попробуйте этот способ. Если да, убедитесь, что ваш класс, который вы пытаетесь запустить, имеет основной метод, то есть такое же определение метода, как показано ниже:

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

Я надеюсь, что это поможет вам.

Создан 18 фев.

Точкой входа для Java-программ является метод:

public static void main(String[] args) {
    //Code
}

Если у вас его нет, ваша программа не запустится.

Я решил это, добавив новую исходную папку и поместив свой java-файл в эту папку. «Исходная папка» — это не просто папка, я считаю. это какой-то специальный тип папки для java/eclipse, и его можно добавить в eclipse, щелкнув правой кнопкой мыши проект -> свойства -> путь к сборке Java -> источник и добавьте папку

ответ дан 22 апр.

Несколько вещей, чтобы проверить:

  1. У вас есть основной пакет? все ваши классы находятся в этом пакете?
  2. Используете ли вы основной класс с public static void main(String[] args)?
  3. Вы объявляете: package ; в вашем основном классе?
  4. Вы всегда можете очистить проект перед его запуском. В Eclipse — просто перейдите в Project -> clean, затем снова запустите приложение.

ответ дан 06 мар ’14, в 15:03

Я столкнулся с той же проблемой. Я исправил, щелкнув правой кнопкой мыши пакет -> свойства -> Путь сборки Java -> Добавить папку (выберите папку, в которой находится ваш код).

Создан 01 сен.

Я запускаю eclipse из Ubuntu. Была такая же проблема, и я смог запустить программу через терминал. Поэтому я просто переместил существующий public static void main(String[] args) { чуть ниже объявления класса (затмение автоматически отформатировало его), и следующий запуск прошел успешно. Затем вернул основной метод туда, где он был раньше, и на этот раз он работал нормально.

ответ дан 30 дек ’15, 18:12

У меня была эта проблема в двух проектах. Maven и командная строка работали, как и ожидалось, для обоих. Проблемы были специфичны для Eclipse. Два разных решения: Проект 1): переместите объявление основного метода наверх в классе, над всеми другими объявлениями, такими как поля и конструкторы. Сумасшествие, но это сработало. Проект 2): Решение для Проекта 1) не устранило проблему. Однако удаление импорта ломбоков и явное написание метода получения решили проблему.

Вывод: Eclipse и/или плагин lombok имеют/имеют ошибку.

Создан 01 июн.

Выглядит слишком поздно, чтобы ответить, но может помочь кому-то,

Имея ту же проблему, я решил ее, выполнив следующие шаги:::::

Выберите «Основной класс в eclipse», затем нажмите «Окно» в строке меню,

Window-->Show view-->Select Outline

Щелкните правой кнопкой мыши на main(String[]):void становятся Run As -> java Application

Ссылка на изображение для метода Running Main

Делая это, вы можете запустить основной метод напрямую. Это сработало для меня

ответ дан 20 мар ’21, в 04:03

Щелкните правой кнопкой мыши> Запустить AS> Запустить конфигурации

На этом экране, если ваше текстовое поле «Основной класс» пусто, добавьте имя класса, нажав кнопку «Поиск» в правой части текстового поля, и выберите файл класса. Затем нажмите кнопку «Выполнить» в нижней части экрана конфигурации. Вот и все

ответ дан 04 мар ’19, в 05:03

Вы должны поместить все свои файлы (file.java) в корневую папку SRC.

Создан 28 фев.

Убедитесь в том, main in public static void main(String[] args) в нижнем регистре. Для меня это не сработало, когда у меня было это с большой буквы.

Создан 21 сен.

Поместите файл основного класса Java в src/main/java папку и проверьте, нет ли ошибок в «Пути сборки Java», щелкнув правой кнопкой мыши проект и выбрав Java Build Path->Source.

ответ дан 15 мая ’19, 07:05

Если вы работаете с проектом Maven, вы должны понимать, что расположение каталогов немного отличается. При этом имя пакета должно быть SRC / основной / Java.

Для этого обновите исходную папку, щелкнув правой кнопкой мыши проект. корневая папка -> свойства -> путь сборки java -> вкладка источника. Здесь удалите все другие исходные папки, так как они могли быть добавлены неправильным образом. Теперь выберите проект /src/main/java в качестве исходной папки. Добавьте и примените изменения. Теперь обновите свое рабочее пространство с помощью F5.

Это должно решить проблему нераспознавания основного типа.

ответ дан 14 авг.

Я столкнулся с той же проблемой и обнаружил, что есть дополнительная пара фигурных скобок (фигурные скобки), заключающая public static void main(String args) {…}. Этот метод действительно должен находиться в верхней части класса и не должен заключаться в фигурные скобки. Кажется, что при работе в Eclipse вокруг этого метода можно получить фигурные скобки. Это может быть только один из способов увидеть эту проблему при работе с Eclipse. Удачного кодирования!

ответ дан 30 апр.

У меня это случалось неоднократно после добавления изображений в проект в Eclipse и включения их в путь сборки. Решение заключалось в том, чтобы щелкнуть правой кнопкой мыши класс, содержащий main метод, а затем выберите «Запуск от имени» -> «Приложение Java». Кажется, когда вы добавляете файл в путь сборки, Eclipse автоматически предполагает, что этот файл находится там, где main метод есть. Проходя через меню «Запуск от имени» вместо простого нажатия зеленой кнопки «Запуск от имени», вы можете указать правильную точку входа.

ответ дан 26 мая ’14, 06:05

При сохранении файла убедитесь, что он имеет расширение .java. Если это не так, Eclipse не сможет прочитать его как java-файл.

Создан 08 сен.

У меня была эта проблема, потому что код учебника, который я пытался запустить, не был в правильном пакете, хотя я ввел имя пакета в начале каждого класса.

Я щелкнул правой кнопкой мыши по каждому классу, Refactor и Move To и принял предложение имени пакета.

Затем, как обычно, Run AsJava Application.

И это сработало :)

Создан 29 июн.

Вы также должны проверить это. Перейдите к пути сборки Java -> путь сборки конфигурации, убедитесь, что системная библиотека JRE [Java SE -версия] отмечена флажком, попробуйте снова запустить код. Это исправило мою проблему.

ответ дан 02 мар ’21, в 16:03

В моем случае я использовал ant для выполнения сборки и явно имел настройку класса в файле build.xml:

<target name="jar">
  <jar destfile="ec-stats.jar" includes="bin/**,src/**">
    <manifest>
        <attribute name="Main-Class" value="my.package.MyStatistics" />
    </manifest>
  </jar>
</target> 

Но он по-прежнему выдавал ту же ошибку, пока я не щелкнул правой кнопкой мыши папку в Eclipse и не выбрал Build Path -> Use As Source Folder.

Введите описание изображения здесь

Смотрите также Ошибка: выделение не содержит основного типа

ответ дан 18 окт ’21, 19:10

Решил проблему следующим образом:

  1. Переход в свойства проекта
  • 1.1) Внутри «Компилятор Java»: выберите: «Уровень соответствия компилятора:» для конкретной версии JDK (в моем случае я выбрал 15)

  • 1.2) Внутри «Путь сборки Java», на вкладке «Библиотеки», в пути к модулю: измените «Системную библиотеку JRE» на ту же версию, которую вы выбрали на шаге 1.1 выше (в моем случае я выбрал JDK 15)

  1. Запустите java-файл, содержащий основной метод

ответ дан 20 окт ’21, 18:10

Это можно решить в два этапа, если вы используете Eclipse IDE.

👉 Шаг I: щелкните правой кнопкой мыши проект и выберите Специалист > Выбрать Обновить проект

👉 Шаг II: выберите проект щелчком Кнопка ОК

Введите описание изображения здесь

Надеюсь, это поможет.✔

ответ дан 26 мар ’22, в 15:03

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

java
eclipse
project
startup
startup-error

or задайте свой вопрос.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Select variable to plot матлаб как исправить ошибку
  • Serum error 534 ошибка