How can I let the user press enter for the default value using a scanner in java?

Suppose I want to receive the following prompt:

"Enter the number of iterations (400):"

Where the user can enter an integer or just hit enter for 400 by default.

How can I implement the default in Java using the Scanner class?

public static void main(String args)
{
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the number of iterations (400): "); 
    input.nextInt();
}

      

As you can see, I must have "nextInt ()", how can I do something like "nextInt or return?", In which case, if it is a return, I will default to 400.

Can anyone point me in the right direction?

+2


source to share


2 answers


I agree with @pjp's answer to your question directly on how to adapt the scanner (I gave it a vote), but I get the impression that the overkill can be survived with Scanner if you only read one value from stdin.The Scanner strikes me as what you would like to use to read a series of inputs (if that's what you are doing, apologies), but otherwise why not just read stdin directly? Although now that I look at it, it's a little more detailed;)

You should probably also handle this IOException better than me ...



public static void main(String[] args) throws IOException
{
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the number of iterations (400): ");

    int iterations = 400;
    String userInput = input.readLine();

    //if the user entered non-whitespace characters then
    //actually parse their input
    if(!"".equals(userInput.trim()))
    {
        try
        {
            iterations = Integer.parseInt(userInput);
        }
        catch(NumberFormatException nfe)
        {
            //notify user their input sucks  ;)
        }
    }

    System.out.println("Iterations = " + iterations);
}

      

+3


source


As we found out earlier, the scanner does not treat the newline as a token. To get around this, we can call nextLine

and then match it using a regular expression.

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    int val = 400;

    String line = scanner.nextLine();

            if (line.matches("\\d+")) {
        Integer val2 = Integer.valueOf(line);
        val=val2;
    }

    System.out.println(val);
}

      



This type makes a redundant scanner. You can also call input.readLine()

.

+2


source







All Articles