+ 2
How can I use next input in a Loop?
Hello, I tried to solve a little thing and I don't know, why it does't work. Can anybody explain, what I'm doing wrong? https://code.sololearn.com/cZtJjGxUmxfs/?ref=app
4 Answers
+ 2
There are two errors. actually.
The first is that you define "number" within the do-while loop. If you do this, the variable's scope is only within the body of the loop, and does not get seen by the while check. You should define this outside and above the loop, though you can still leave the nextInt() call and assignment within the loop body.
Second, read is not defined. Yeah, nowhere. read.nextInt() does not work because there is no instantiation of the Scanner class named "read". Only scan exists, and you should swap out read for it.
On a side note, you should probably swap out a new prompt for the final else if, it's a copy of the one above it.
+ 1
Thank you!
I'm two steps for. Just still don't know, how I can use Input in a loop.
+ 1
If you wish to loop your input, that's relatively simple. As I said in my previous answer, you can define "number" outside the loop, then assign it the value returned by scan.nextInt(), ie:
int number;
do{
number = scan.nextInt();
//if-else if-else chain
}while(number != 0);
Thought in my opinion, you don't really have to use a do-while loop here. Instead, you can use a less intuitive, but more concise coding pattern such as this:
int number;
while( (number = scan.nextInt() ) != 0){
//.....if-else if-else chain
}
Because, just like the +, -, *, /, % operators, the assignment operator (=) is an expression as well, and it returns the left hand side, or the variable assigned to the expression.
0
It works!
Thank you so much!!!!