Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax error, 'for each' statements are only available if source level is 1.5 or greater

Tags:

java

Receiving the below error:

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 at Tuto.OneDimArrays.main(OneDimArrays.java:14)

CODE:

public class OneDimArrays {    
    public static void main(String[] args) {            
        int[] xabc = new int[5];    
        xabc[2]=20;    
        xabc[0]=50;    
        for(int temp:xabc){    
        System.out.println(temp);   
        }
    }
}

Please help..

like image 248
user3220565 Avatar asked Jan 25 '14 21:01

user3220565


3 Answers

If you are using Eclipse IDE then right click on the project, goto properties, Java Compiler, Check Enable project specific settings and set the Compiler compliance level to greater than 1.5. I solved this issue by setting it to 1.6. Hope it helps

like image 104
Waqas Khalid Obeidy Avatar answered Nov 05 '22 01:11

Waqas Khalid Obeidy


The error tells you exactly what the problem is. You are using a for-each loop:

for(int temp : xabc)
{
    System.out.println(temp);   
}

This syntax was only added in Java 1.5, so you appear to be compiling using an earlier version. Without knowing what IDE/environment you're using, I can't tell you how to fix this, but see if you can find a way to compile your code using a more up-to-date version of java.

Note that there is a difference between the JRE (Java Runtime Environment) and the JDK (Java Development Kit). The JRE is used to run java programs on your computer, while the JDK is used to write java programs on your computer. Normally your system only warns you when the JRE is outdated (as most computer users don't write code and probably don't even have the JDK installed). Therefore, even if your JRE is up to date, you won't be able to compile the latest features unless you have the right JDK.

If you're using an old JDK, you can download the latest version here.

If you're using an up-to-date JDK, you will have to change some settings in your project in order to use it.

If for whatever reason neither of these are an option, you can emulate the for-each loop using pre-1.5 language constructs. The most basic approach is described in Pat's answer.

like image 3
ApproachingDarknessFish Avatar answered Nov 05 '22 03:11

ApproachingDarknessFish


Compile this in a later version of java if you can.

If you are unable to use a later version of java for some reason just use a regular for loop:

for(int i = 0; i < xabc.length; i++) {
    int temp = xabc[i];
    System.out.println(temp);
}
like image 2
Pat Avatar answered Nov 05 '22 01:11

Pat