Java exception in thread main java lang error unresolved compilation problems

Java. Кто может помочь с «Eclipse»? Вопрос внутри.

Текст программы такой:
class ss public static void main(String args[]) String command = «cancel»;
switch (command) case «connect»:
System.out.println(«Connecting»);
break;
case «cancel»:
System.out.println(«Canceling»);
break;
case «disconnect»:
System.out.println(«Disconnecting»);
break;
default:
System.out.println(«Command Error!»);
break;
>
>
>

У меня на компьютере версия JVM последняя — 1.8. В этом легко убедиться с помощью запроса из cmd.
При компиляции программы «Eclipse» (тоже последней версии) говорит:
«Exception in thread «main» java.lang.Error: Unresolved compilation problem:
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted».
Как ему объяснить, что это не так? Где поставить нужную галочку? Только подробно, если можно, я новичок.

Посмотрите Project —>Properties —> Java Compiler, then select Enable projects specific settings and select Compiler Compliance Level 1.8. And under the Java Build Path libraries, there is JRE1.8.0-45.

И вместо JRE выберите JDK.

Если не поможет, а очень надо реализовать такой функционал, замените кучкой if(command.equals(«. «)) и т. д. . Или сделать массивчик с командами и в switch уже использовать номер

Спасибо за ответ, но почему он мне даже не предлагал выбрать эти варианты. Прилагаю скриншоты.
А насчет другого пути, так рано или поздно это опять всплывет. Где-то в другом месте.

Поставила на Win 10 на ноутбук «Eclipse mars», без настройки переменных сред даже. И эта программа запустилась! Но что делать на стационарном, не знаю. Старый «Эклипс» удалила, поставила «Марс» . Одно и то же.

Dimentr Гуру (3925) Скачал марс тоже, при установке он меня что-то спрашивал про JRE, указал на 1.8, всё встало хорошо и код работает. Вижу этот парадокс на скринах, эклипс видит 1.8, но не даёт использовать, да?) Не знаю как с таким бороться. Я бы удалил все jre и jdk, которые есть, удалил эклипс. Поставил jdk 1.8, поставил эклипс. В таком случае у него просто не будет других вариантов кроме как использовать 1.8 🙂

Пробовали переустановить или юзать другие IDE? Инструкция по установке библиотек:
Create new project>В блоке JRE галочку на первый вариант и выбираете JavaSE-1.8

Переустанавливать — слишком радикально, и ничего не изменится. Юзать — тоже нет. Поставила галочку на JavaSE-1.7, т. к. JavaSE-1.8 не было варианта. В общем, ничего не изменилось, кроме ошибки: «Exception in thread «main» java.lang.Error: Unresolved compilation problem:

Читайте также:  Javascript добавить элемент ассоциативный массив

Денис Рамусь Гуру (2930) Прошу прощение, а почему Eclipse? Попробуйте Intelij Idea. А по теме Windows->Preferences->Installed JRE кнопочка add и выберите путь к JDK. В новом проекте выберите версию USE a project sperific JRE и выберите вашу.

Источник

How to resolve java.lang.Error: Unresolved compilation problem

Unresolved compilation problems in the code are due to compilation errors in the code.
Many problems can be detected if we use an IDE like IntelliJ, Eclipse IDE, etc. This is a very generic error and there could be multiple reasons to get this error.

Error

Let’s see a sample error that has a typo in the method name.

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The method printl(String) is undefined for the type PrintStream

Unresolved compilation problem

Fix

As we can see in the Error stack trace, printl(String) is undefined for the type PrintStream.

There is a typo in the method name: printl

The correct method name is println()

IDE

Using IDE would detect this kind of error and prompt the developer with fixes. In this case, if we hover the mouse would show the correct method names for the class.

Another Example

Exception in thread “main” java.lang.Error: Unresolved compilation problem:

Fix: The project is configured with modules. An there is a missing entry for the required module module-info.java. Add the required module in the file and save the file.

module Sample
requires java.desktop;
>

Источник

Unresolved Compilation Problem

send pies

posted 6 years ago

  • Report post to moderator
  • Hi!
    My network flow problem doesn’t seem to work because of an unresolved compilation problem.

    Marshal

    Python

    send pies

    posted 6 years ago

  • Report post to moderator
  • Hello Neyla, welcome to the Ranch!

    You forgot to tell us what the compilation error you’re seeing is?

    Tim Driven Development | Test until the fear goes away

    Bartender

    send pies

    posted 6 years ago

  • Report post to moderator
  • I copied your code right in to Intellij and it compiles fine and even runs (waits for input).

    What error are you getting?

    send pies

    posted 6 years ago

  • Report post to moderator
  • Exception in thread «main» java.lang.Error: Unresolved compilation problem:

    that’s the error i get in eclipse..

    Bartender

    send pies

    posted 6 years ago

  • Report post to moderator
  • Does the class belong to any package named aww? If so it should be under the package called aww, and we don’t see any package statement in your code.

    Читайте также:  Java temporal to date

    Bartender

    send pies

    posted 6 years ago

  • Report post to moderator
  • Swastik Dey wrote: Does the class belong to any package named aww? If so it should be under the package called aww, and we don’t see any package statement in your code.

    That’s really strange. I copied and pasted the code right into Intelli and it had no issues and even ran.

    Try the community (free) edition of Intellij as a test.

    I don’t think it’s your code.

    And, I did zero configuration chores.

    author

    jQuery Chrome

    send pies

    posted 6 years ago

  • Report post to moderator
  • Just took one of my other code (managed by eclipse), and removed the package statement, but still kept it in the package. Eclipse will complain about something like «declared package AAA does not match BBB blah blah blah».

    Additionally, ran that broken code (even though it has an error). eclipse will complain, and popup to confirm.. and forced eclipse to run anyway. The resultant error message at console was «unresolved compilation problem: at xxx.yyy.main(zzz.java)». just like as mentioned by the OP.

    So, it is two problems. One, eclipse is configured to expect the class in the package, but with the code, the class is not in the package. And two, the error message is ignored; the application is forced to run, forcing eclipse to print out a nonsensical message, because that information is lost at run time.

    Now, is the missing package the underlying cause? or did the OP simply didn’t cut and paste it? . This is not clear. There is no visibility into that. The OP need to tell us what the compilation errors are, and not just tell us the errors when forcing the application to run.

    Источник

    Java не видит класс

    Всем привет, 2 день обучения Java и тут столкнулся с проблемой, компилятор не видит мой класс(пробовал создать дополнительный класс, а в нем main , но тоже не помогло).

    Exception in thread «main» java.lang.Error: Unresolved compilation problem: The constructor Marine() is undefined

    Указываю параметры для конструктора:

    Marine Test = new Marine(abc,qwe,asd,fds,qwe); 

    имя_параметра cannot be resolved to a variable

    The constructor Marine() is undefined

    это при наведения на ошибку в консоле, та же ошибка.

    Если удалить конструктор, то ошибка исчезнет, но суть задания именно в конструкторе.

    import java.util.Scanner; import java.lang.Math.*; import java.util.Random; import java.lang.String; public class Marine < public static String name_unit; public static String name_ship; public static String type_of_ship; public static String date; public static String operating_time; public static String personnel; public static String place; public static boolean result; public Marine(String name_unit, String name_ship, String type_of_ship, String date, String operating_time ) < this.name_unit = name_unit; this.name_ship = name_ship; this.type_of_ship = type_of_ship; this.date = date ; this.operating_time = operating_time; >public String GetName_Unit() < return name_unit; >public void SetName_Unit(String name_unit) < this.name_unit = name_unit; >public String GetType_Of_Ship() < return type_of_ship; >public void set(String type_of_ship) < this.type_of_ship = type_of_ship; >public String GetDate() < return date; >public void setDate(String date) < this.date = date; >public String GetOperating_time() < return operating_time; >public void setOperating_time(String operating_time) < this.operating_time = operating_time; >public String GetPersonnel() < return personnel; >public void setPesonnel(String personnel) < this.personnel = personnel; >public String GetPlace() < return place; >public void setPlace(String place) < this.place = place; >public boolean GetResult() < return result; >public void setResult(boolean result) < this.result = result; >public String toString() < return "Название части: " + name_unit + " Название корабля: " + name_ship + " Тип корабля: "+ type_of_ship + " Дата учений: " + date + " Наработка: " + operating_time + " Кол-во личного состава: " + personnel + " Место проведения: " + place + " Результат учений: " + result ; >public static void main (String[] args) < Marine Test = new Marine(); // вот здесь ошибка, пишет класс не //определен >> 

    Ответы (2 шт):

    Пропишите класс ваш класс отдельно от выполняемого класса с методом main
    В исполняемый класс импортируйте созданный вами класс и передайте в методе main в конструктор параметры экземпляра, либо сделайте перегрузку конструктора без параметров, но при этом обязательно инициализировать поля класса что бы все они не были null.

    Читайте также:  Java spring error code

    По умолчанию у класса есть конструктор без параметров, который Вы и вызываете в main, но как только мы добавляем любой другой конструктор, нам нужно добавить его вручную, т. к. конструктор без параметров, который не делает ничего, больше не считается валидным. Обычно имена в java пишутся CamelCase, при этом имена переменных и методов с маленькой буквы. Инициализировать статические поля в конструкторе не стоит. Тем более делать для них не статические геттеры и сеттеры. Потому как статические поля доступны без создания экземпляра класса. Лучше создать класс Marine в отдельном файле, сделать все его поля private без static. А в классе, в котором находится метод main, сделать его импорт, создать через один из доступных конструкторов и взаимодействовать с ним через открытые public методы.

    Источник

    Оцените статью