Search code examples
javajava.util.scanner

How do you take an undefined amount of inputs from scanner?


I am making a search engine to find what document matches the words given by the user. The following is my code:

Scanner userInput = new Scanner(System.in);
System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
String[] stringArray = new String[10];
int i = 0;

// Takes input until user leaves a blank line or max is reached.
while (userInput.hasNext() && i < 9){
   stringArray[i] = userInput.next();
   i++;
}

for (int j = 0; j < i; j++){
   System.out.println(stringArray[j]);
}

This is my method that actually takes the user input and I am going to add to it in a little bit to do the search but I tried to test this much (that's why it prints out the input) to see if it works but It keeps accepting input. What can I change so that it takes as many words as the user puts them until they leave a line blank? I got it to stop at 10 but I thought hasNext() would stop it when they leave a line blank but it just keeps scanning.


Solution

  • hasNext() & next() stop at words, not lines. With your code, the user could put all 10 words on the same line and they'd be done. Also, these methods will skip all whitespace, including newline characters, until they find the next word. You can't look for a blank line using hasNext() and next() can never return an empty string. You want hasNextLine() and nextLine() instead.

    Scanner userInput = new Scanner(System.in);
    System.out.println("\n\n\nEnter the words you would like to search your documents for (up to 10):");
    String[] stringArray = new String[10];
    int i = 0;
    
    while (i < stringArray.length 
            && userInput.hasNextLine()
            && !(stringArray[i] = userInput.nextLine().trim()).isEmpty()) {
        i++;
    }
    
    for (int j = 0; j < i; j++) { // just for testing purposes
        System.out.println(stringArray[j]);
    }
    

    But why limit yourself to just 10 lines? You can use ArrayList instead for more flexibility:

    Scanner userInput = new Scanner(System.in);
    System.out.println("\n\n\nEnter the words you would like to search your documents for:");
    List<String> stringList = new ArrayList<>();
    String line;
    
    while (userInput.hasNextLine()
            && !(line = userInput.nextLine().trim()).isEmpty()) {
        stringList.add(line);
    }
    
    stringList.forEach(System.out::println); // just for testing purposes