-1

I currently am using try scannerIn.nextInt() = x, where x was initialized as an int from the start. So if the user enters anything besides an integer, it catches the exception and asks again, which is dandy.

My issue is that, if the user enters something like eleven eleven eleven, or 11 11 11, the spaces messes it all up since each separate input is counted separately instead of all at once.

scannerIn.nextLine() would only work for a string correct? How do I read a whole line at once so it throws the exception that they did not enter a single answer, regardless of type?

Eli Sadoff
  • 6,628
  • 6
  • 29
  • 54

2 Answers2

0

With Scanner the default delimiters are the whitespace characters. but you can change the delimeter to something like new line.

Scanner s = new Scanner(input).useDelimiter("[\r\n]+");

root
  • 2,692
  • 1
  • 16
  • 24
0

You can create a method to check if user input is valid, and ask for it until it is.

Check this:

import java.util.Scanner;

public class mainProgram
{

    public static void main ( String [ ] args )
    {
        boolean cont = true;
        Scanner sc;
        String userInput;
        while(cont)
        {
            sc = new Scanner(System.in);
            System.out.print("Enter numbers separated by space ");
            userInput = sc.nextLine ( );

            if( checkInput ( userInput ))
            {
                cont = false;
            }
            else
            {
                System.out.println ( "Bad input, try again" );
            }
        }
        System.out.println ( "Finished successfully" );


    }

    public static boolean checkInput( String userInput )
    {
        if ( userInput.length ( ) == 0)
        {
            return false;
        }

        String [ ] numbers = userInput.trim ( ).split ( " " );
        for(String number : numbers)
        {
            try
            {
                Integer.parseInt ( number );
            }
            catch ( Exception e )
            {
                return false;
            }
        }

        return true;
    }

}
Rcordoval
  • 1,792
  • 1
  • 15
  • 24