3

Lets say I wanted to have the following prompt:

"Enter the number of iterations (400):"

Where, the user can enter an integer or simply hit enter for the default of 400.

How can I implement the default value 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 a return?", in which case if it is a return I'll default the value to 400.

Can anyone point me in the right direction?

2 Answers2

3

I agree with @pjp for answering your question directly on how to adapt the scanner (I gave him an up-vote), but I get the impression using Scanner is kinda overkill if you're only reading in one value from stdin. Scanner strikes me as something you would more want to use to read a series of inputs (if that's what you're doing, my apologies), but otherwise why not just read stdin directly? Although now that I look at it, it's kinda verbose ;)

You should also probably handle that IOException better than I did...

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);
}
Brent Writes Code
  • 19,075
  • 7
  • 52
  • 56
2

As we found out earlier Scanner doesn't treat new line 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 kind of makes the scanner redundant. You might as well call input.readLine().

pjp
  • 17,039
  • 6
  • 33
  • 58