Search code examples
javainputuser-input

Reading input till end of line in java


I have a switch statement that asks the user to input some data.

For case 2: the user is supposed to enter data like below.

1081 678 873 1438 1276 1243 428

The programme will read every nextInt and add it to an array. My problem is with the below method, the program waits for another line to be keyed in. It does not carry on executing the code after appending the input data to the array.

switch(option) {
    case 1: Do something;
            break;
                    
    case 2:             
        ArrayList <Integer> ciphertext = new ArrayList <Integer>();
    
        System.out.print("Enter the ciphertext: ");
                    
        do {                    
            int cipher = input.nextInt();
            ciphertext.add(cipher);
        }
                    
        while (input.hasNextInt());

        input.close();

        someMethod();
        break;
                
    case 3:
        break;

}                   

I tried the methods in this thread & the ones mentioned in this, however I still get the same results.

I tried a different method by asking the user to key in '-1' and the end of the data and by creating a 'do -while' condition to loop through the input data until it hits the '-1'. This method works, however I do not want the user to key in additional characters other than the data necessary.


Solution

  • According to the docs of Scanner.hasNextInt():

    Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt method.

    The way i understand it, there has to be input in order to return if the next input is integer, if there is no input, it waits for it.

    Also consider this input - 1081 678 873 1438 1276 as 1243 428. Reading will stop once non integer input is reached - as in this case, and you are unaware that there is invalid input and skipped input.

    I suggest to read the entire line with Scanner.nextLine, then split it to an array using desired delimiter.

    String line = input.nextLine();
    String[] data = line.split("\\s+");
    

    Iterate the array, parse each value in it and add to the list.