Just going through the sample Scala code on Scala website, but encountered an annoying error when trying to run it.
Here’s the code: http://www.scala-lang.org/node/45. On running it on Eclipse, I got this message ‘Editor does not contain a main type’ that prevents it from running.
Is there anything I need to do…i.e break that file into multiple files, or what?
asked Jul 11, 2009 at 13:32
Helen NeelyHelen Neely
4,5818 gold badges39 silver badges64 bronze badges
0
In Eclipse, make sure you add your source folder in the project properties -> java build path -> source. Otherwise, the main() function may not be included in your project.
answered Mar 28, 2011 at 20:34
milkplusmilkplus
32k7 gold badges30 silver badges31 bronze badges
2
I have this problem a lot with Eclipse and Scala. It helps if you clean your workspace and rebuild your Project.
Sometimes Eclipse doesn’t recognize correctly which files it has to recompile
Edit:
The Code runs fine in Eclipse
OpiesDad
3,3152 gold badges15 silver badges30 bronze badges
answered Jul 11, 2009 at 15:04
nuriaionnuriaion
2,6012 gold badges23 silver badges18 bronze badges
4
A simpler way is to close the project and reopen it.
answered Jul 22, 2010 at 22:43
staticstatic
3113 silver badges2 bronze badges
1
You have to make sure that your .java files are in the .src folder in eclipse. I had the same exact problem until I got it figured out.
answered Feb 29, 2012 at 14:40
ultra99ultra99
4131 gold badge7 silver badges11 bronze badges
0
Just make sure that the folder you work in is added to the built path:
right-click
your folder —> build Path
—> Use as source Folder
and it should now find main
therein.
Sandra Rossi
11.5k3 gold badges22 silver badges44 bronze badges
answered May 16, 2013 at 13:56
kholofelo Malomakholofelo Maloma
9433 gold badges15 silver badges26 bronze badges
1
You can try to run the main function from the outline side bar of eclipse.
answered Apr 1, 2015 at 20:15
FeiFei
5816 silver badges7 bronze badges
1
I had the same problem. I tried all sorts of things. And I came to know that
- My .java files were not linked and
- they were not placed in the ‘src’ folder.
Things I did:
Project properties >> Java Build Path >> Source
- Deleted the original ‘src’ folder which was empty using ‘Remove’ option
- Added the source that contained my source .java files using the ‘Add Folder’ option
This solved the error.
Torsten
1,6162 gold badges21 silver badges41 bronze badges
answered Jun 12, 2014 at 4:12
0
Just close and reopen your project in Eclipse. Sometime there are linkage problems. This solved my problem
answered Feb 26, 2016 at 8:12
Mohit SinghMohit Singh
5,8292 gold badges23 silver badges25 bronze badges
0
A quick solution:
First, exclude the package:
Right click on the source package >> Build Path >> Exclude
Then include it back:
Right click on the source package >> Build Path >> Include
answered Feb 20, 2011 at 14:27
What you should do is, create a Java Project, but make sure you put this file in the package file of that project, otherwise you’ll encounter same error.
shanethehat
15.4k11 gold badges56 silver badges87 bronze badges
answered Feb 9, 2011 at 22:15
That code is valid. Have you tried to compile it by hand using scalac? Also, have you called your file «addressbook», all lowercase, like the name of the object?
Also, I found that Eclipse, for some reason, set the main class to be «.addressbook» instead of «addressbook».
answered Jul 11, 2009 at 14:39
Daniel C. SobralDaniel C. Sobral
293k86 gold badges497 silver badges679 bronze badges
1
you should create your file by
selecting on right side you will find your file name,
under that will find src folder their you right click select —>class option
their your file should be created
agf
167k42 gold badges283 silver badges234 bronze badges
answered Aug 11, 2011 at 11:48
Make sure that your .java file is present either in the str package, or in some other package. If the java file with the main function is outside all packages, this error is thrown.
answered Jul 1, 2014 at 8:46
0
Have faced the similar issue, resolved this by right clicking on the main method in the outline view and run as Java application.
answered Nov 10, 2017 at 6:27
0
I just had this problem too. The solution is to make sure eclipse created the project as Java project. Just create a new Java project and copy your class into the src folder (and import the eventual dependencies). This should fix the problem.
answered Apr 15, 2010 at 7:54
KullDoxKullDox
3531 gold badge3 silver badges11 bronze badges
1
The correct answer is: the Scala library needs to before the JRE library in the buildpath.
Go to Java Buildpath > Order and Export and move Scala library to the top
answered Feb 23, 2011 at 4:22
I had this problem with a Java project that I imported from the file system (under Eclipse Helios). Here’s a hint: the src code didn’t seem to be compiled at all, as no «bin» directory showed up.
I had to create a Java project from scratch (using the wizard), then compare the .project
files of the non-working and working projects.
The project giving «Editor does not contain a main type» had this as the «buildSpec» in the .project file:
<buildSpec>
</buildSpec>
But the working project had this as the «buildSpec»:
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
I copied this in, and the imported project worked.
I know my answer is for Java, but the same might be the issue for your Scala project.
answered Mar 12, 2014 at 0:28
May be the file you have created is outside the src(source) folder. Trying to call the class object(from the file located in the src folder) from the .java file outside the source folder results in the same error. Copy .java file to the source folder, then build it. The error will be gone.
answered Mar 21, 2014 at 6:52
Vamsi TallapudiVamsi Tallapudi
3,4051 gold badge13 silver badges23 bronze badges
I had the same problem. I had the main class out of the src package, in other folder. I move it in and correct folder and solved
answered Aug 5, 2015 at 16:08
run «eclipse -clean -refresh» from command line. This fixed the issue for me when all other solutions failed.
answered Feb 12, 2016 at 1:19
MikeGMikeG
111 bronze badge
This could be the issue with the Java Build path.
Try below steps :
- Go to project properties
- Go to java Build Path
- Go to Source tab and add project’s src folder
This should resolve the issue.
answered Jan 4, 2017 at 14:09
AalekhGAalekhG
3513 silver badges8 bronze badges
If it is maven project please check the java file is created under src/main/java
If you are not getting please change the JRE path and create the java files in above folder structure
answered Apr 26, 2017 at 13:06
ssomussomu
797 bronze badges
For me, in Eclipse 3.6, this problem occurs when my main method is not public. I caused the problem by having a main method like this:
static void main(String[] args)
The dubugger was unable to detect this by itself. I am pretty suprised Eclipse overlooked this.
answered Jun 21, 2011 at 3:28
djangofandjangofan
27.6k57 gold badges188 silver badges283 bronze badges
In the worst case — create the project once again with all the imports from the beginning. In my case none of the other options worked. This type of error hints that there is an error in the project settings. I once managed to solve it, but once further developments were done, the error came back. Recreating everything from the beginning helped me understand and optimize some links, and now I am confident it works correctly.
answered Jun 20, 2012 at 8:19
SergiuSergiu
3494 silver badges8 bronze badges
Follow the below steps:
- Backup all your .java files to some other location
- delete entire java project
- Create new java project by right click on root & click new
- restore all the files to new location !!
Unni Kris
3,0614 gold badges33 silver badges57 bronze badges
answered Jan 23, 2012 at 15:57
File >> Import >> Existing Projects into Workspace >> Select Archive Filed >> Browse and locate file >> Finish. If its already imported some other way delete it and try it that way. I was having the same problem until i tried that.
answered Apr 4, 2013 at 0:52
One more thing to check: make sure that your source file contains the correct package declaration corresponding to the subdirectory it’s in. The error mentioned by the OP can be seen when trying to run a «main type» declared in a file in a subdirectory but missing the package statement.
answered Nov 28, 2013 at 22:45
I have this problem too after I changed the source folder. The solution that worked for is just editing the file and save it.
answered Aug 24, 2014 at 10:32
HunsuHunsu
3,2317 gold badges29 silver badges62 bronze badges
Try ‘Update Project’. Once I did this, The Run as Java Application option appeared.
answered Oct 25, 2015 at 20:56
In my particular ‘Hello World’ case the cause for this problem was the fact, that my main()
method was inside the Scala class
.
I put the main()
method under the Scala object
and the error disappeared.
That is because Scala object
in Java terms is the entity with only static members and methods inside.
That is why Java’s public static void main()
in Scala must be placed under object
.
(Scala class
may not contain static’s inside)
answered Jan 28, 2016 at 20:46
Vlad.BachurinVlad.Bachurin
1,3401 gold badge14 silver badges22 bronze badges
So in this tutorial, We will know that what kind of reasons can be for getting this error “Editor does not contain a main type” and we will see how to fix this error.
Basically, this type of Error means your Editor is not able to find the “main” method in any of your current program classes. The editor shows this error because when you want to run the project, at that time, the interpreter couldn’t find the main function to start the execution of the program.
Reasons for Error
So there can be various reasons causing this error:
- If you have not declared the main method in your program, at that time it will be compiled successfully but while running the program, it will throw this error.
- It can occur if the .java file has not linked or has not placed in the src
- If you have not added a build path in the same folder where you are working.
- If .class file or project file is not present in your workspace at that time it will occur.
- If you are using Eclipse for java Programming and you have not declared the main method as public.
- If the program is not compiled correctly.
Solutions
- First, you should check that you have declared the “main” method in your program or not if you have not then you should write the “main” method inside your class.
- If you are using eclipse and you have declared the “main” method in your program and you have written it inside the class then you have to check that you have added the build path or not. If you have not added then:- go to project properties -> Choose java build path -> Click on the source.
- If the editor is not able to find the Source folder then you have to follow these steps:-
-
- Right-click on Project folder and go through the Properties
- Choose ‘Java Build Path’.
- Click on the ‘Sources’ tab on top.
- Click on ‘Add Folder’ on the right panel.
- Select your folders and apply them.
- If you have not to clean your project then you should try this, Project -> Clean, or you can follow these steps on the command line -> run “eclipse -clean -refresh.
- In the last, confirm that you have declared the main method with “public” access specifier, like ->
public static void main(String[] args) { //body } |
- And if you are sure about this that you have written the main method and code correctly then delete the current program file after copying your code and create a new file and paste in it.
- Please Check that .class file is present in your workspace or not, If there is not present that file then you should add that file by compiling it before running the Project.
- Wherever you have written the “main” method, you should sure about this that It is present inside the src folder, if It’s not then you have to place the “main” method inside the src folder and after that, you could simply run the Program.
- If the program is not compiled correctly that time project does not contain an executable main class, So that time you have to compile the program correctly.
That was all about the reasons and solutions to this “Editor does not contain a main type”. If you have any queries or suggestions please leave in the comment below. We would love to help.
Я загрузил eclipse-jee-kepler-SR1-linux-gtk-x86_64.tar.gz
. Это затмение встроено с java, а мой Lubuntu — 64-битный. Всякий раз, когда я компилирую и запускаю простой код в java, как показано ниже:
public class Sample{
public static void main(String[] args){
System.out.println("YOLO");
}
}
Я всегда получаю Editor does not contain a main type
.
Я помещаю файл в папку проекта с именем Sample
. Это затмение должно скомпилировать java-код, потому что его дистрибутив IDE специализируется на java.
Как я могу решить эту ошибку?
Любая помощь будет высоко оценена.
Здесь моя структура проекта:
09 июнь 2014, в 12:08
Поделиться
Источник
15 ответов
Я подозреваю, что проблема заключается в том, что Sample.java должен находиться в пакете внутри папки src.
Я думаю, что затмение не будет автоматически смотреть за пределы.
phil_20686
09 июнь 2014, в 11:29
Поделиться
У меня была такая же проблема. Это будет звучать безумно, но если кто-то увидит это, попробуйте это до решительных мер. удалить подпись метода:
public static void main(String args[])
(Не является телом объявления основного простого метода)
Сохраните проект, а затем повторно напишите заголовок метода обратно на его соответствующий корпус. Сохраните снова и снова запустите. Это сработало для меня, но если он не работает, попробуйте еще раз, но очистите проект прямо перед повторным запуском.
Я не знаю, как это исправлено, но это произошло. Стоит ли задуматься, прежде чем воссоздать весь проект?
ThatOneGuy
23 март 2015, в 07:15
Поделиться
Проблема в том, что ваша папка не идентифицирована как папка источника.
- Щелкните правой кнопкой мыши папку проекта → Свойства
- Выберите «Java Build Path»
- Нажмите на вкладку «Источники» вверху
- Нажмите «Добавить папку» на правой панели
- Выберите свои папки и примените
Ramraj
29 апр. 2018, в 14:34
Поделиться
Щелкните правой кнопкой мыши свой проект > Запустить как > Запустить конфигурацию… > Приложение Java (в левой боковой панели) — дважды щелкните по нему. Это создаст новую конфигурацию. нажмите кнопку поиска в разделе «Основной класс» и выберите из него свой основной класс.
Ninad Pingale
09 июнь 2014, в 10:18
Поделиться
Для меня запись classpath в файле .classpath
не указывает на нужное место. После изменения его в <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"/>
исправлена проблема
Siva Srinivas
15 май 2018, в 18:58
Поделиться
Создать исходную папку в разделе Ресурсы Java
sarath
10 фев. 2015, в 11:13
Поделиться
Убедитесь, что вы выполняете как > Java-приложение.
Если нет, вы можете попробовать Project > Clean
Еще несколько вопросов, которые касаются этого, которые могут быть полезны,
Обратитесь к этому вопросу
Cyrex
09 июнь 2014, в 10:20
Поделиться
Сначала найдите основной метод или нет. Если он есть, перезапустите свое затмение и щелкните правой кнопкой мыши на странице с основным методом. Перейдите в качестве приложения Java.
Sudhir Gaurav
13 июнь 2018, в 20:56
Поделиться
Щелкните правой кнопкой мыши на своем проекте, выберите «Создать» → «Исходная папка»
Введите имя src as Folder, затем нажмите «Готово».
Затем Eclipse распознает папку src как содержащую Java-код, и вы должны иметь возможность настроить конфигурацию прогона
Brendan Cody-Kenny
03 март 2018, в 22:18
Поделиться
Я установил Eclipse и создал проект Java.
Создал новый файл Java за пределами каталога src и попытался запустить его.
У меня такая же ошибка: «Редактор не содержит основного типа».
Я просто переместил java файл в папку src и мог просто запустить программу.
Я не мог понять, что другие ответы просят попробовать. Это было так просто.
Piyush Aggarwal
28 дек. 2017, в 12:02
Поделиться
Щелкните правой кнопкой мыши на файле Sample.java и удалите его. Теперь перейдите в File → New → Class, введите имя программы (например, hello), нажмите «Готово». Он создаст файл hello.java. Введите исходный код программы и окончательно нажмите ctrl + F11
Pavan Yogi
06 окт. 2017, в 06:05
Поделиться
У меня была такая же проблема. Я случайно удалил файл .classpath и .project в моей рабочей области. К счастью, это было в корзине, как только оно было восстановлено, проблем не было.
Pradeep AR
05 авг. 2017, в 23:15
Поделиться
В идеале исходный код должен находиться в пакете src/default, даже если вы не указали имя пакета. По какой-то причине исходный файл может находиться вне папки src. Создайте в папке scr, он будет работать!
Shiyas Cholamukhath
01 авг. 2017, в 07:47
Поделиться
поместите основной класс метода в папку src (в среде Eclipse).
Kranthi kiran
16 апр. 2018, в 10:15
Поделиться
Просто измените «String [] args» на «String args []».
Sonu Mishra
31 дек. 2017, в 09:23
Поделиться
Ещё вопросы
- 0MySQL Broken Rank
- 0Пользовательское форматирование на время с использованием Moment.js
- 1Добавьте точки Openlayers на карту как один слой
- 0Все переключается на стиль переключения
- 0переменная объема не отражена в директиве
- 0От загруженного iframe для iframe не получено сообщение vaild
- 0Могу ли я получить значение из std :: map без сбоя, если ключ не существует?
- 1Установка полей в ячейке таблицы слов программно с помощью c #
- 1java.lang.IllegalArgumentException: dataSource или jdbcTemplate требуется при запуске tomcat
- 0Являются ли типы указателей единственным способом «предотвращения» вызова конструктора в объявлении?
- 1Уровень доступа к базе данных ASP.NET MVC
- 0Ошибка ActiveXObject при запуске из приложения HTML или приложения Flex
- 0изолировать объекты друг от друга, angularjs
- 1Насмешливый PrintQueue в .NET
- 1Линейный график становится пустым (показывает большой красный х)
- 1чтение байтов без использования цикла
- 1Python 2.7 split и .col конкатенация
- 1Поднимите все вхождения типа во вложенном словаре до ключа верхнего уровня
- 0Как получить объект данных из тега в IE8
- 1Нестандартное использование уведомления об ожидании в параллельных программах Java
- 0AngularJS Предварительная настройка фильтра
- 0phpseclib не возвращает результатов даже по простой команде
- 0HTML выбор тега по умолчанию показывает пустым на IE10
- 1Значение типа «Стиль» нельзя добавить в коллекцию или словарь типа «UIElementCollection».
- 1Параметры всплывающего окна «Всплывающее окно» в Android?
- 1Секретные ключи различаются между Android и сервером
- 0Laravel 5 Internal Server Error 500 и TokenMismatchException для обновления базы данных с помощью AngularsJS
- 1Программа закрывается при загрузке файла
- 0Ошибка разрешения Angular и Devise
- 0Пытаюсь выучить винапы. сделал первую программу, которая должна показать мне окно. CMD показывает но нет окна
- 0выберите порядок по заголовкам товаров в группе
- 0Сбой теста rspec, но его нужно пройти
- 1Динамические маркеры на карте?
- 1C # программа зависает на Socket.Accept ()
- 0Получить значение из динамически сгенерированного массива
- 0Как выполнить среднее для аналогичной группы записей в MySQL
- 0Ограничение загрузки изображений в jpg в ASP .NET MVC
- 0Как получить доступ к данным без повторения ng
- 0Какую самую низкую скорость jQuery можно установить?
- 0Хотите знать, будет ли это работать как один оператор if () [closed]
- 0Заголовок изображения появляется до того, как изображение полностью исчезло
- 1Java regex работает в моей системе, но не на сервере
- 0Angularjs — угловая 1.4.4 нг-модель на выборочном поле возвращает недопустимые значения
- 0Запретить прямой URL вместо перенаправления на виртуальный хост
- 0Как получить массив CURL JSON только в ZF2
- 1Как получить последний элемент в массиве Node.js? [Дубликат]
- 0Скрыть содержимое таблицы, не вкладывая его в столбец
- 0функции isupper (), islower (), toupper (), tolower () не работают в c ++
- 0Проблема с функциями GPB SerializeTo
- 0Удаление маркеров в Google Maps Места Сервисы
score:38
Accepted answer
I have this problem a lot with Eclipse and Scala. It helps if you clean your workspace and rebuild your Project.
Sometimes Eclipse doesn’t recognize correctly which files it has to recompile
Edit:
The Code runs fine in Eclipse
score:-1
You need locate file .java
in folder src
(in Project Explorer of Eclipse) and then it run.
I have just add a file .java
into project and it isn’t in folder src
, so I have a same error.
I put again it into src
, then it was build.
score:-1
Instead of adding File, add class. File
->New
->Class
. That fixed my issue.
score:-1
Add a main method method inside the class to overcome this problem. I was facing the same issue regarding this.Now Including the main method inside my code i resolved my problem.
score:0
For me, in Eclipse 3.6, this problem occurs when my main method is not public. I caused the problem by having a main method like this:
static void main(String[] args)
The dubugger was unable to detect this by itself. I am pretty suprised Eclipse overlooked this.
score:0
Follow the below steps:
- Backup all your .java files to some other location
- delete entire java project
- Create new java project by right click on root & click new
- restore all the files to new location !!
score:0
In the worst case — create the project once again with all the imports from the beginning. In my case none of the other options worked. This type of error hints that there is an error in the project settings. I once managed to solve it, but once further developments were done, the error came back. Recreating everything from the beginning helped me understand and optimize some links, and now I am confident it works correctly.
score:0
File >> Import >> Existing Projects into Workspace >> Select Archive Filed >> Browse and locate file >> Finish. If its already imported some other way delete it and try it that way. I was having the same problem until i tried that.
score:0
One more thing to check: make sure that your source file contains the correct package declaration corresponding to the subdirectory it’s in. The error mentioned by the OP can be seen when trying to run a «main type» declared in a file in a subdirectory but missing the package statement.
score:0
I have this problem too after I changed the source folder. The solution that worked for is just editing the file and save it.
score:0
Try ‘Update Project’. Once I did this, The Run as Java Application option appeared.
score:0
In my particular ‘Hello World’ case the cause for this problem was the fact, that my main()
method was inside the Scala class
.
I put the main()
method under the Scala object
and the error disappeared.
That is because Scala object
in Java terms is the entity with only static members and methods inside.
That is why Java’s public static void main()
in Scala must be placed under object
.
(Scala class
may not contain static’s inside)
score:0
On reason for an Error of: «Editor does not contain a main type»
Error encountered in: Eclipse Neon
Operating System: Windows 10 Pro
When you copy your source folders over from a thumb-drive and leave out the Eclipse_Projects.metadata folder.
Other than a fresh install, you will have to make sure you merge the files from (Thrumb-drive)F:Eclipse_Projects.metadata.plugins .
These plug-ins are the bits and pieces of library code taken from the SDK when a class is created. I really all depends on what you——import javax.swing.*;—— into your file. Because your transferring it over make sure to merge the ——Eclipse_Projects.metadata.plugins—— manually with a simple copy and paste, while accepting the skip feature for already present plugins in your Folder.
For windows 10: you can find your working folders following a similar pattern of file hierarchy.
C:Users>Mikes Laptop> workspace > .metadata > .plugins <—merge plugins here
score:1
I had this problem with a Java project that I imported from the file system (under Eclipse Helios). Here’s a hint: the src code didn’t seem to be compiled at all, as no «bin» directory showed up.
I had to create a Java project from scratch (using the wizard), then compare the .project
files of the non-working and working projects.
The project giving «Editor does not contain a main type» had this as the «buildSpec» in the .project file:
<buildSpec>
</buildSpec>
But the working project had this as the «buildSpec»:
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
I copied this in, and the imported project worked.
I know my answer is for Java, but the same might be the issue for your Scala project.
score:1
May be the file you have created is outside the src(source) folder. Trying to call the class object(from the file located in the src folder) from the .java file outside the source folder results in the same error. Copy .java file to the source folder, then build it. The error will be gone.
score:1
I had the same problem. I had the main class out of the src package, in other folder. I move it in and correct folder and solved
score:1
run «eclipse -clean -refresh» from command line. This fixed the issue for me when all other solutions failed.
score:1
This could be the issue with the Java Build path.
Try below steps :
- Go to project properties
- Go to java Build Path
- Go to Source tab and add project’s src folder
This should resolve the issue.
score:1
If it is maven project please check the java file is created under src/main/java
If you are not getting please change the JRE path and create the java files in above folder structure
score:2
I just had this problem too. The solution is to make sure eclipse created the project as Java project. Just create a new Java project and copy your class into the src folder (and import the eventual dependencies). This should fix the problem.
score:2
The correct answer is: the Scala library needs to before the JRE library in the buildpath.
Go to Java Buildpath > Order and Export and move Scala library to the top
score:3
That code is valid. Have you tried to compile it by hand using scalac? Also, have you called your file «addressbook», all lowercase, like the name of the object?
Also, I found that Eclipse, for some reason, set the main class to be «.addressbook» instead of «addressbook».
score:3
you should create your file by
selecting on right side you will find your file name,
under that will find src folder their you right click select —>class option
their your file should be created
score:3
Make sure that your .java file is present either in the str package, or in some other package. If the java file with the main function is outside all packages, this error is thrown.
score:3
Have faced the similar issue, resolved this by right clicking on the main method in the outline view and run as Java application.
score:4
What you should do is, create a Java Project, but make sure you put this file in the package file of that project, otherwise you’ll encounter same error.
score:4
A quick solution:
First, exclude the package:
Right click on the source package >> Build Path >> Exclude
Then include it back:
Right click on the source package >> Build Path >> Include
score:6
Just close and reopen your project in Eclipse. Sometime there are linkage problems. This solved my problem
score:7
I had the same problem. I tried all sorts of things. And I came to know that
- My .java files were not linked and
- they were not placed in the ‘src’ folder.
Things I did:
Project properties >> Java Build Path >> Source
- Deleted the original ‘src’ folder which was empty using ‘Remove’ option
- Added the source that contained my source .java files using the ‘Add Folder’ option
This solved the error.
score:7
You can try to run the main function from the outline side bar of eclipse.
score:23
Just make sure that the folder you work in is added to the built path:
right-click
your folder —> build Path
—> Use as source Folder
and it should now find main
therein.
score:28
You have to make sure that your .java files are in the .src folder in eclipse. I had the same exact problem until I got it figured out.
score:31
A simpler way is to close the project and reopen it.
score:90
In Eclipse, make sure you add your source folder in the project properties -> java build path -> source. Otherwise, the main() function may not be included in your project.
Related Query
- 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
- Editor does not contain main type in Eclipse
- Eclipse Editor does not contain a main type
- Editor does not contain a main type — messed up Build path config
- Editor does not contain a main type in sample project
- Error: Selection does not contain a main type
- Java launch error selection does not contain a main type
- Editor does not contain a main type, even though it does
- Selector does not contain a main type eclipse
- 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
- generated Xpand code ‘ editor does not contain a main type’. However I have a main method
- Eclipse error: «Editor does not contain a main type»
- Eclipse error: ‘Selection does not contain a main type/an applet’
- Eclipse saying selection does not contain a main type?
- Why do I get a «Selection does not contain a main type» message in Eclipse?
- «Selection does not contain a main Type» — Eclipse Run Error
- Not able to create executable jar for webdriver+TestNg project which does not contain main method in any class
- Imported project in Eclipse doesn’t run, says — ‘Editor does not contain a main type.’
- AspectJ causing «Editor does not contain a main type» error
- Eclipse error with archived java projects «editor does not contain main type»
- ERROR: Does not contain source for Thread.class — Class File Editor
- Eclipse error when trying to run Java application — «Selection does not contain a main type» — But it does?
- Why do I get the «Selection does not contain a main type» when my class has a main?
More Query from same tag
- Eclipse IDE debugging servlet code a variable is not registered in the Variables tab
- Open Eclipse both old and new(clean)
- Only want to ever see Allman style code and save K&R style code
- Maven Eclipse plugin and classpath issues in Eclipse
- how draw in realtime to tableLayout — in android with eclipse
- Sending a command line command from JButton?
- ClassCastException when registering Saveable in UI thread
- StringBuilder.toString() is printed as empty string in Eclipse-console when too big?
- How to select an older API version in Android graphical editor?
- Cant seem to connect the JDBC sql server driver to java eclipse project
- Signing apk’s — what does it mean and how do I do it?
- What Eclipse should I download if I program in java?
- How to resolve “DesiredCapabilities cannot be resolved to a type»?
- How do I get Eclipse to ignore errors in WSDL file?
- Protocol Buffers with Android & Eclipse : NoClassDefFoundError
- Change Line Feeds from CRLF to LF in Eclipse
- IBM rational application developer does not start on ubuntu
- eclipse/sts environment always set to production
- android project contains error (eclipse) but not visible
- Eclipse — where is the java option?
- static final field in public nested class
- Turn off Eclipse formatter for selected code area?
- How to call results of a Boolean method in a main method
- Two different data sources in a Weblogic server
- develop eclipse plugin for existing desktop application
- How to organize Windows and Android builds of my C++ game?
- Processing with JBox2d Hellow World issue
- Writing test case for Junit testing
- Android: error while installing v7 appcompat (app compat library)
- Prevent SWT ScrolledComposite from eating part of it’s children
Recommended Answers
Well, if Eclipse «shows that there are errors and warnings» then that class is probably not being compiled and so the project does not contain an executable main class. Fix the «errors and warnings», first.
Jump to Post
Click the Src package u have made, i think you must clicked some library and running the application….
Jump to Post
it will be very easy for us if u take two or three snapshot of your screen and load here………….
Jump to Post
I’ve already told you that until it compiles there is nothing to execute.
And, as far as being new goes, then you need to start with something simpler, such as the official tutorials.
Jump to Post
This is not helping at all, guys. I don’t want to change anything written in those classes because they seem to be built on the top of each other.
What would you like us to do to help you? Please believe that we cannot change the way that Java works. …
Jump to Post
All 23 Replies
masijade
1,351
Industrious Poster
Team Colleague
Featured Poster
11 Years Ago
Well, if Eclipse «shows that there are errors and warnings» then that class is probably not being compiled and so the project does not contain an executable main class. Fix the «errors and warnings», first.
11 Years Ago
Click the Src package u have made, i think you must clicked some library and running the application….
11 Years Ago
I clicked on SRC then imported the packages I wanted to run with their accompanying files that support them.
@ Masijade, These packages and projects are from a book. Therefore, they are not written for readers to complete them; they’re meant to help readers understand how an app works and play around with the code.
11 Years Ago
it will be very easy for us if u take two or three snapshot of your screen and load here………….
masijade
1,351
Industrious Poster
Team Colleague
Featured Poster
11 Years Ago
@ Masijade, These packages and projects are from a book. Therefore, they are not written for readers to complete them; they’re meant to help readers understand how an app works and play around with the code.
Okay? And? How does that change anything I said? If it doesn’t compile it is not a main class. It is an attempt at a main class, but until it compiles there is nothing for Eclipse to execute.
11 Years Ago
It is strange that eclipse doesn’t find any code to execute. How do you think I can possibly fix the issue?
Edited
11 Years Ago
by rotten69 because:
n/a
11 Years Ago
Please post pictures….. I already told u , no body guess what the problem is.
stultuske
1,116
Posting Maven
Featured Poster
11 Years Ago
well .. just posting
public static void main(String[] args){
says nothing. for all we know, this main method is declared within another method.
so, show the error message (stacktrace, …) you get, and post some code in which we can see something.
masijade
1,351
Industrious Poster
Team Colleague
Featured Poster
11 Years Ago
It is strange that eclipse doesn’t find any code to execute. How do you think I can possibly fix the issue?
You said that Eclipse «shows errors». Well, how do you propose that Eclipse execute anything that isn’t compiled? This is not a scripting language, you know. As I said, fix those errors.
11 Years Ago
Are u sure ur java file is in src folder ??
11 Years Ago
they are supposed to be in the src folder ,but when I imported the files, the child files got into their parent folder (well, they were in their parent folder)if this makes sense.
a.oprea
0
Junior Poster in Training
11 Years Ago
I remember having a similar problem, it was saying couldn’t find the main, but it was there… I think I solved it just by refreshing the src folder in eclipse, not sure anyway. And I don’t know why it said that in the first place
11 Years Ago
These are the print-screen images as requested before and hopefully are illustrating well to you guys. Looking forward to getting a solution to this problem from you all. Thanks in advance.
cheers,
JamesCherrill
4,667
Most Valuable Poster
Moderator
Featured Poster
11 Years Ago
You have 689 uncorrected compile-time errors. Yet you say
It is strange that eclipse doesn’t find any code to execute. How do you think I can possibly fix the issue?
There won’t be any code to execute until the compiler generates some. The compiler won’t compile your code until you fix the errors. Start with the first error and keep fixing them until they are all fixed. Then you will get some code to execute.
ps: Such a large number of errors suggests that you have problems with your project setup, eg incorrect path(s) — but the detailed messages will spell it out for you.
11 Years Ago
Bear in mind that I’m still new to Java language..
JamesCherrill
4,667
Most Valuable Poster
Moderator
Featured Poster
11 Years Ago
Bear in mind that I’m still new to Java language..
That may be so, but Java and Eclipse work the same way regardless of your experience
masijade
1,351
Industrious Poster
Team Colleague
Featured Poster
11 Years Ago
I’ve already told you that until it compiles there is nothing to execute.
And, as far as being new goes, then you need to start with something simpler, such as the official tutorials.
11 Years Ago
This is not helping at all, guys. I don’t want to change anything written in those classes because they seem to be built on the top of each other.
11 Years Ago
I never ever down-voted on all forums where I member of, you are 1st. candidate during this month, are you thinking about that all posters in this thread just wasted her/his time for your …., everything is wrong
11 Years Ago
There are alot error. If you want to make them run then try to solve each error, eclipse is one of the best Java visual editor tool, simply bring cursor over the error and it will provide you help that how to resolve that error. U can post more problem after that , finally every thing will start working.
JamesCherrill
4,667
Most Valuable Poster
Moderator
Featured Poster
11 Years Ago
This is not helping at all, guys. I don’t want to change anything written in those classes because they seem to be built on the top of each other.
What would you like us to do to help you? Please believe that we cannot change the way that Java works. You have a project with over 800 errors. There’s nothing that anybody on Earth can do to make that work without fixing the errors.
If you have any religious beliefs then maybe praying will work for you.
Good luck.
J
javaAddict
900
Nearly a Senior Poster
Team Colleague
Featured Poster
11 Years Ago
From the screenshot, I assume that you took all the files form somewhere else and put them in eclipse? If that is the case, then I see that you took the .java files and the .class files and put them in same folder src/
I think, without knowing your settings, that since the .class files are in the src/ folder it doesn’t find them because you haven’t set the classpath to see them.
Even if changing the classpath to look at the src folder might make you project compile it is not the right way. The .class files should be put in a different folder
Also if you have code that works but what you have written that uses that, doesn’t compile is probebly because you haven’t set the classpath to «see» it.
Go to the Project properties and look at the java build path or search for tutorials about how to set the classpath with eclipse.
11 Years Ago
I solved the problem by just declaring a package name which was undeclared before and Eclipse did not complain about it.
Thanks all,
Reply to this topic
Be a part of the DaniWeb community
We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.
Posted by3 years ago
Archived
Me and my friends are making a game for our project in class, and we uploaded everything to github so we can work on at home, and I just imported to eclipse, and its giving me the «editor does not contain main type» error when I try to run driver, even though there is a main in driver.
This thread is archived
New comments cannot be posted and votes cannot be cast
level 1
Find the main class, right click > Run > As Java Application.
level 1
You can try clean and rebuild your project otherwise Right click on the project folder and go to Properties
Then Choose ‘Java Build Path, click on the sources, add folder, add your folders, then apply
level 2
i did that but now my project icon has a little black * on it, and the files inside the src folder that i made (also has a black *) all have green pluses.
level 1
I fixed this problem by making a new java project, and copy-pasting the files. Something was wrong with the project when I manually added the src folder
So I am trying to learn Java, but for some reason when ever I try to run my program in Eclipse I get this:
As you can see, the program is very simple (the first program I am supposed to write), so I don’t know what’s going on!
I haven’t been able to find the log in the workspace/.metadata/.log
folder as specified on the eclipse wiki and nothing appears when I launch eclipse from the terminal.
If it matters at all I installed eclipse from the archive downloaded from http://developer.android.com/sdk/index.html because I was originally going for learning how to make Android apps (then I figured I ought to learn Java first. :D)
Anyways, does anyone know what is causing this error and how to fix it?
Thanks!
asked Dec 20, 2013 at 1:11
RPiAwesomenessRPiAwesomeness
9,60321 gold badges70 silver badges104 bronze badges
Well, I just realized after much deliberation and reading that facepalm I had forgot the public static void main() { }
!
Wow. Anyways, it’s now working and I am marking this as answered.
answered Jan 27, 2014 at 14:36
RPiAwesomenessRPiAwesomeness
9,60321 gold badges70 silver badges104 bronze badges