Ilja Veselov
Ilja Veselov

Reputation: 99

How to exit from while loop with condition Scanner hasNext()

Found the solution below on Hyperskills.org (considered as correct solution) - can anybody explain how this code can work if while loop is endless? I mean (scanner.hasNext()) is always true.

Scanner scanner = new Scanner(System.in);
     ArrayList<String> questList = new ArrayList<>();

     while (scanner.hasNext()) {
         String nextGuest = scanner.next();
         questList.add(nextGuest);
     }

     Collections.reverse(questList);

     questList.forEach(System.out::println);

Upvotes: 0

Views: 1923

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

You can break the infinite loop based on some condition e.g. in the code given below, I have used while(true){} which is an infinite loop which will run until the user enters quit (case-insensitive).

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> questList = new ArrayList<>();

        while (true) {// Infinite loop
            String nextGuest = scanner.next();
            if (nextGuest.equalsIgnoreCase("quit")) {
                break;
            }
            questList.add(nextGuest);
        }

        Collections.reverse(questList);

        questList.forEach(System.out::println);
    }
}

A sample run:

a1
b2
c3
quit
c3
b2
a1

Upvotes: 1

Paul.L
Paul.L

Reputation: 21

The while loop will keep going while the scanner has another token in its input. Inside the while loop, you are advancing the scanner with scanner.next(), so the scanner isn't stationary. So eventually scanner.hasNext() will be False.

Upvotes: 0

Related Questions