Java input validation for multiple entries on the same line with Scanner

how to take multiple string input in java using scanner
validating string input java
java input validation numbers only
validate user input using java chars and strings
java input validation loop
java scanner
how to validate user input in java
java scanner only accept numbers

I'm using the Scanner to get an integer input from a user. In this case the integer should be between 5 and 10 inclusive.

I have this working with this code:

import java.util.Scanner;

public class valin {

    public static void main(String[] args) {

        int inputNumber;

        Scanner in = new Scanner(System.in);

        do {
            System.out.println("Enter a number between 5 and 10: ");

            while (!in.hasNextInt()) {
                System.out.println("That is not a number. Please try again: ");
                in.next();
            }

            inputNumber = in.nextInt();

            if (inputNumber < 5 || inputNumber > 10) {
                System.out.println("Needs to be a number between 5 and 10. Try again.");
            }

        } while (inputNumber < 5 || inputNumber > 10);

        System.out.println("You entered: " + inputNumber);
        in.close();

    }

}

The problem I have is when the user inputs more than 1 input on a line. In this case my code will display as:

Enter a number between 5 and 10: 
www eee
That is not a number. Please try again: 
That is not a number. Please try again: 
qqq 6
That is not a number. Please try again: 
You entered: 6  

What I want is if the user enters for example "qqq 6" or any "input whitespace input" that the code will tell the user it is invalid and to enter it again.

Is this possible?


Here's a working version catching NumberFormatException, as suggested by a few other people:

import java.util.Scanner;

public class valin {

  public static void main(String[] args)
  {
    Integer inputNumber = -1;

    Scanner in = new Scanner(System.in);

    System.out.println("Enter a number between 5 and 10: ");

    while(in.hasNextLine()){
      String line = in.nextLine().trim();

      try{
        inputNumber = Integer.parseInt(line);
      }catch (NumberFormatException nfe){
        System.out.println("That is not a number. Please try again.");
        continue;
      }

      if(inputNumber >= 5 && inputNumber <= 10){
        System.out.println("You entered: " + inputNumber);
        break;
      }else{
        System.out.println("That is not a number between 5 and 10. Please try again.");
      }
    }

    in.close();

  }

}

How to take the input of a line of integers separated by a space in C , How do you accept multiple inputs on the same input line? Is there a way to get multiple inputs on one line? Yes the user should be able to enter multiple input values on one line. Have you tried it? What did you try to enter? Remember not to press Enter until all the values have been entered for the line. Your example shows the input on 2 lines: 5 on the first and 4 on the second.


put your "in" var in a string [] variable, then check for each element if it is an integer

How do I make Java register a string input with spaces?, , one may write something like this: for (i=1; i<=n; i++) { Java input validation for multiple entries on the same line with Scanner The problem I have is when the user inputs more than 1 input on a line. In this case my


Here's an alternative way to do it using regular expressions:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class valin {

  private static final Pattern INT_5_TO_10 = Pattern.compile("[5-9]|10");

  public static void main(String[] args)
  {
    int inputNumber;

    Scanner in = new Scanner(System.in);

    System.out.println("Enter a number between 5 and 10: ");

    while(in.hasNextLine()){
      String line = in.nextLine().trim();
      Matcher m = INT_5_TO_10.matcher(line);

      if(m.matches()){
        inputNumber = Integer.parseInt(line);   //Only neccessary if you want to use this later on, otherwise we don't need to parse the number
        System.out.println("You entered: " + inputNumber);
        break;
      }else{
        System.out.println("That is not a number between 5 and 10. Please try again.");
      }
    }

    in.close();

  }

}

Java Actually: A First Course in Programming, Input validation is the responsibility of the calling method, in this case the main() Reading multiple values per line Using the Scanner class, we can also read Reading multiple values from the same line on the keybouard. import java.util. Java User Input. The Scanner class is used to get user input, and it is found in the java.util package. To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:


The problem with your code is in the line

inputNumber = in.nextInt();

The entered input with white space will be readed and parsed twice. So you can use

String input = in.nextLine();

to take the input from the user and then parse this string input to Integer using

inputNumber = Integer.parseInt(input);

So that you can overcome by above mentioned problem.

The code Integer.parseInt(input) may results in NumberFormatException. Please handle the necessary exception.

How do I validate input when using Scanner?, To validate input the Scanner class provides some hasNextXXX() method that can be use to validate input. package org.kodejava.example.util; import java.​util. If these posts help, you can support me, buy me a cup of coffee or tea. So how can I get the input to display on the same line as the println? But with Java 1.5, a new class — called Scanner — was introduced to simplify the task of getting input from the user. Here, you use the Scanner class to get simple input values from the user. The techniques that I present here are used in many of the programs shown in the rest of this book.


This is "tighter" version of the solution provided by @James Baker that uses capturing group in the regular expression and try with resources

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    private static final Pattern INT_5_TO_10 = Pattern.compile("([5-9]|10)");

    private static int parse(String line) {
        Matcher m = INT_5_TO_10.matcher(line.trim());
        return m.matches() ? Integer.parseInt(m.group(1)) : -1;
    }

    public static void main(String[] args) {
        int inputNumber;
        try (Scanner in = new Scanner(System.in)) {
            System.out.println("Enter a number between 5 and 10: ");

            while (in.hasNextLine()) {
                String line = in.nextLine();
                inputNumber = parse(line);

                if (inputNumber > 0) {
                    System.out.println("You entered: " + inputNumber);
                } else {
                    System.out.println("That is not a number between 5 and 10. Please try again.");
                }
            }
        }
    }
}

Taking input in Java : Scanner class, Same as nextInt() is used to input an integer value, methods to input values of other data types are listed below. Method, Inputs. nextInt(), Integer. nextFloat(), Float. Please help me to solve the problem of taking multiple integer input in a single line using BufferedReader class? In Scanner class we can take multiple input like all elements of array in one line.


java.util.Scanner.nextLine java code examples, How can I read input from the console using the Scanner class in Java? @​param prompt text * @return A string containing the line read from the console */ private String readLine(String prompt) Entry<String, Class> classEntry : clazzMap.


How to declare multiple input statement in a single line in java , How to declare multiple input statement in a single line in java ??? and then their values may be assigned to a and b, using the parseInt The Scanner object can parse user input directly, so we don't have to And, the user may input both integers on the same line, or even on different lines, as desired.


Why is Scanner skipping nextLine() after use of other next functions , How to validate identifier using Regular Expression in Java · Average of Cubes of first N natural numbers Since this method continues to search through the input looking for a line separator, it may nextLine() method of Scanner Class. import java.util.Scanner;. public class ScannerDemo1 { Print the values to check.