Java for loop not working

I hope this is not a stupid question, but I looked at every example that I can find, and it still seems that I have this code correctly and it still does not work ... I enter one number and it moves to the next a line of code, not a loop. I use this to populate an array with 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]; } 
+7
source share
7 answers

; at the end of the for loop, it is taken as an empty statement, the equivalent of an empty block for your for loop. The compiler reads 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 ; to get your intentional behavior.


If you do not need i outside the loop, you can transfer its declaration to 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 an erroneous semicolon was present ; , there would be a compilation error that previously warned you of the error ; . The compiler will 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 of why good practice is to limit the scope of variables when possible.

+16
source

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

+7
source

remove the last dot with a semicolon from the loop line ............

+4
source

To avoid this error in the future, you should always use a new variable in a for loop. Instead:

 for (i = 0; ... 

records

 for (int i = 0; ... 

Thus, this would be a compile-time error, since the variable I would not be in scope in the next block.

+4
source

There should not be a semicolon at the end of the first line. It indicates that your loop is empty.

+3
source

The answer has already been given, but I would like to add that if you use IDE * there will probably be a warning for these types of empty statements and the other is easy to do, it is easy to miss the type of errors (instead of comparison, for example, comparison).

0
source

so that you know. something like that:

 for(;;) ; 

should send your program on hold. happened to me in the early days. :)

0
source

All Articles