5

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?

2

2 Answers 2

10

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

You can use a do-while for post loop condition checking

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.