0

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.

AtlasUser5
  • 81
  • 6
  • What is your required ending condition? I mean you can simply change the condition in the loop to end, for example: 1) after a predefined hardcoded number of entries, 2) after the user enters a stopping keyword (for example *quit*), 3) after a number of entries which the user gives at the start of input, and so on... – gthanop Jul 06 '21 at 14:02
  • Hi @gthanop I wanted to save data in real time to a database, since the data is string and can be anything I don't know what quit criteria to set, For Example : if the quit criteria for user is to type **TERMINATE** the loop should stop but at the same time **TERMINATE** can be the entry user need to save in database. – AtlasUser5 Jul 06 '21 at 14:49
  • 1
    Special control character (EOF) to cause `hasNextLine` to return false: https://stackoverflow.com/a/16206876/2711811 –  Jul 06 '21 at 15:07

1 Answers1

0

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.

gthanop
  • 3,035
  • 2
  • 10
  • 27