Reputation: 99
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
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
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