Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to assign a variable in a while loop?

Tags:

java

I'm looking for a way to use scanner in a while loop, without advancing twice.

String desc = "";
while (!scanner.next().equals("END")) {
    desc = desc + scanner.next();
}           

As you can see, when scanner.next() is called in the while loop's condition and inside of the while loop itself. I want it to advance the scanner only once. Is there any way to do that?

like image 598
Axel Avatar asked Dec 25 '22 19:12

Axel


1 Answers

Yes it is possible. You should also check that the Scanner has more tokens in its input

String desc = "";
String next = null;
while (scanner.hasNext() && !(next = scanner.next()).equals("END")) {
    desc = desc + next;
}
like image 100
Omar Mainegra Avatar answered Dec 28 '22 09:12

Omar Mainegra