The following question states:
"Write a loop that reads positive integers from standard input and that terminates when it reads an integer that is not positive. After the loop terminates, it prints out, on a line by itself, the sum of all the even integers read. Declare any variables that are needed. ASSUME the availability of a variable, stdin, that references a Scanner object associated with standard input".
The answer is as follows:
int even = 0;
int i = 1;
while (i > 0){
i = stdin.nextInt();
if ((i % 2)==0 && (i > 0)){
even = i;
}
}
System.out.print(even);
Why does the int variable "i" need to be set to a numerical value for the code to work? I can't seem to figure out why.
CodePudding user response:
int i;
while (i > 0){
Looking at these lines -- just these lines, nothing else -- should the while loop run, or not?
There's no way to tell without setting i.
CodePudding user response:
Why does the int variable "i" need to be set to a numerical value for the code to work? I can't seem to figure out why.
Your local variable 'i' has to be initialized at least one line before it is used, because otherwise you'd be attempting to access a memory cell that has not been initialized, and since Java does not allow you to access the previous content of a memory cell, it'll give you a compile error.
While not recommended, you can leave a variable uninitialized, but you'll have to initialize it at least one line before using it.
Another solution, if for some reason you don't want to initialize 'i', is to use a do-while loop instead of a while-loop:
int even = 0;
int i;
do {
i = stdin.nextInt();
if ((i % 2)==0 && (i > 0)){
even = i;
}
} while (i > 0)
System.out.print(even);