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];
}
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.
Noticed the ';' at the end of for(i=0; i<9; i++); ? ^_^
remove the last character semicolon from for loop line ............
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With