I'm learning Java and one of the examples of the book runs perfectly from command line, but throws an error from Eclipse. The script is this:
/**
* This program displays a greeting from the authors.
* @version 1.20 2004年02月28日
* @author Cay Horstmann
*/
public class Welcome
{
public static void main(String[] args)
{
String[] greeting = new String[3];
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[2] = "and Gary Cornell";
for (String g : greeting)
System.out.println(g);
}
}
The error I get in Eclipse is 'Exception in thread "main" java.lang.Error: Unresolved compilation problem: Syntax error, 'for each' statements are only available if source level is 1.5 or greater' The book says I would get an error in that line (the for) if the JDK was too old, but then why does it run well from the command line? Thanks
-
You probably haven’t set up your jdk for eclipse at all. Make sure you go into your class path and verify it has a reference to your jdk.Nick Humrich– Nick Humrich2014年05月12日 21:53:34 +00:00Commented May 12, 2014 at 21:53
-
You probably have a version of java newer than 1.5 installed in JAVA_HOME, but have your compiler compliance level < 1.5 in your eclipse settings.azurefrog– azurefrog2014年05月12日 21:53:49 +00:00Commented May 12, 2014 at 21:53
-
Try this: stackoverflow.com/questions/1944468/…EyeOfTheHawks– EyeOfTheHawks2014年05月12日 21:57:13 +00:00Commented May 12, 2014 at 21:57
2 Answers 2
Right click on your project --> properties and change version in below screen
enter image description here
The reason is because your Eclipse instance uses a different version of Java compared to when run from the command line.
In order to check which java version is being used as default, type java -version on the command prompt
C:>java -version
java version "1.6.0_45" Java(TM) SE Runtime Environment (build 1.6.0_45-b06) Java HotSpot(TM) Client VM (build 20.45-b01, mixed mode, sharing)
In order to check the Java version that your eclipse instance uses, check out
Welcome Project-->Properties--> Java Build Path--> Libraries--> JRE System Library.
You can verify the Java version for your project from the package explorer as well. enter image description here