Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compilation Error at Enhanced For-Loop. i is already defined in main method but I need integer i for the for loop

Hello StackOverflow Community.

I was working on a Java program using Arrays and 12 integer inputs to then find evens, odds, and negatives and separate them into 3 different arrays.

The program looks as though it should compile and run as intended but it gives me an error at the enhanced for loop saying that variable i is already defined in method main(java.lang.String[])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I already looked at this post and it did not help me with my for-loop issue.
Java: Variable is already defined in method

Here is the program:

public static void main(String[] args){
Scanner in = new Scanner(System.in);
      
int [] twelveInt = new int [12];
      
int countEven = 0;
      
int countOdd = 0;
      
int countNeg = 0;
      
int i = 0;
      
for (i = 0; i < twelveInt.length; i++) {
    System.out.println("Enter the #" + (i + 1) + " integer.");
    twelveInt [i] = in.nextInt();
  
    if (twelveInt[i] % 2 == 0){
        countEven++;
    }
    if (twelveInt[i] % 2 != 0){
        countOdd++;
    }
    if (twelveInt[i] < 0){
        countNeg++;
    }          
}

    
int [] evens = new int [countEven];    
int [] odds = new int [countOdd];
int [] negatives = new int [countNeg];
    

countEven = 0;
countOdd = 0;
countNeg = 0;
    

for (int i : twelveInt) {
        if (i % 2 == 0){
            evens[countEven++] = i;
        }
        if (i % 2 != 0){
            odds[countOdd++] = i;
        }
        if (i < 0){
            negatives[countNeg++] = i;
        }          
    }
          
System.out.println("Here are the Even numbers you entered");
System.out.println(Arrays.toString(evens));
      
System.out.println("Here are the Odd numbers you entered");
System.out.println(Arrays.toString(odds));
      
System.out.println("Here are the Negative numbers you entered");
System.out.println(Arrays.toString(negatives));

Any help with this strange bug is greatly appreciated.

>Solution :

int i = 0;
      
for (i = 0; i < twelveInt.length; i++) {

Change it to this:

for (int i = 0; i < twelveInt.length; i++) {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading