Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java for loop not working

I hope this isn't a stupid question but I have looked up every example I can find and it still seems like I have this code right and it still isn't working... I enter one number and it moves on to the next line of code instead of looping. I'm using this to fill an array with user input numbers. I appreciate any help, thanks.

for(i=0; i<9; i++);
{  
    System.out.println ("Please enter a number:");  
    Num[i] = keyboard.nextDouble();  
    Sum += Num[i];      
    Product *= Num[i];      
}   
like image 993
Steve Avatar asked Jan 01 '11 12:01

Steve


4 Answers

The ; at the end of the for loop is taken as an empty statement, the equivalent of an empty block for your for-loop. The compiler is reading your code as:

int i;
....
for(i=0; i<9; i++)
    /* no-op */;

/* inline block with no relation to for-loop */
{  
    System.out.println ("Please enter a number:");  
    Num[i] = keyboard.nextDouble();  
    Sum += Num[i];      
    Product *= Num[i];      
} 

Remove the ; to get your intended behavior.


If you don't need the i outside of the loop, you could move its declaration within the for statement.

for(int i=0; i<9; i++)
{
   // `i` is only usable here now
}
// `i` is now out of scope and not usable

Using this syntax when the erroneous semicolon ; was present would have produced a compile error that would alerted you to the erroneous ; earlier. THe compiler would see this:

for(int i=0; i<9; i++)
    /* no-op */;

/* inline block with no relation to for-loop */
{  
    System.out.println ("Please enter a number:");  
    Num[i] = keyboard.nextDouble();     // compile error now - `i` is out-of-scope
    Sum += Num[i];      
    Product *= Num[i];      
} 

This would be an example why it is good practice to limit the scope of variables when possible.

like image 191
Bert F Avatar answered Sep 23 '22 18:09

Bert F


Noticed the ';' at the end of for(i=0; i<9; i++); ? ^_^

like image 29
kellogs Avatar answered Sep 21 '22 18:09

kellogs


remove the last character semicolon from for loop line ............

like image 39
Sagar Varpe Avatar answered Sep 23 '22 18:09

Sagar Varpe


To avoid this mistake in future you should always use a fresh variable in a for loop. Instead of:

for (i = 0; ...

write

for (int i = 0; ...

That way it would be a compile-time error, since the variable i would not be in scope in the following block.

like image 26
Roland Illig Avatar answered Sep 21 '22 18:09

Roland Illig