Alternative for an infinite loop in java while using scanner.hasNext() with scanner argument System.in

438 views Asked by At

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.

1

There are 1 answers

0
gthanop On

Since you require that the user can enter any valid String as 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:

import java.util.Scanner;

public class App {
    public static void main(String[] args) throws Exception {

        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter number of entries: ");
        String[] wordsArray = new String[scanner.nextInt()];
        scanner.nextLine(); //Skip the end of the line which contains the user's number of entries.
        
        for (int i = 0; i < wordsArray.length; ++i) {
            System.out.print("Entry " + (i + 1) + ": ");
            wordsArray[i] = scanner.nextLine();
        }
        
        for (String word : wordsArray)
            System.out.println(word);
    }
}

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:

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

public class App {
    public static void main(String[] args) throws Exception {

        Scanner scanner = new Scanner(System.in);
        
        ArrayList<String> wordsList = new ArrayList<>();
        
        do {
            System.out.print("Entry " + (wordsList.size() + 1) + ": ");
            wordsList.add(scanner.nextLine());
            System.out.print("Enter an empty/blank line to insert another word, or anything else to stop and exit: ");
        }
        while (scanner.nextLine().trim().equals(""));
        
        for (String word : wordsList)
            System.out.println(word);
    }
}

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.