Infinite loop using System.in and scanner.hasNext()
While taking input from user and storing it in a list newcomer(like me) generally thinks of using Scanner class for input and check for next input from user with hasNext() method as below. But often forgets the program will keep asking the user to provide input never endingly. What happens is as each time user press enter the hasNext() method thinks another input is generated and loop continues (Keep in mind pressing enter multiple times wont make a difference).
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
List<String> wordsList = new ArrayList<String>();
while (scanner.hasNextLine())
wordsList.add(scanner.nextLine()); // Keeps asking user for inputs (never ending loop)
scanner.close();
for (String word : wordsList)
System.out.println(word);
}
}
Que. What are the working alternatives for above process which let user dynamically decide number of inputs without mentioning the total inputs anywhere.