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

Time:02-26

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[])

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.

CodePudding user response:

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

Change it to this:

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