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.
Since you require that the user can enter any valid
Stringas input, then you can:Option 1:
The user can enter the number of entries they are going to give, before they give them. So then you only need to loop for the requested number of times. For example:
Option 2:
If even the user does not know from the beggining how many entries they want, then you can ask them after every entry, like so:
I know that this (the second) option may be a bit boring for the user to enter every time if they want to quit or not, but the only thing they have to do in order to quit the program (from the second option) is to type anything which will produce a non empty/blank line. They can simply hit a single ENTER key to continue giving entries.