Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate scanner user input in if statement WITHOUT variables

Purpose is to reduce the number of variables so instead of making many variables I want to do something like this:

Scanner scnr = new Scanner(System.in); 

int number = 0;

scnr.nextInt();  

if (((scnr.nextInt() >= 4) && (scnr.nextInt() <=10))) 
{
   number = scnr.nextInt();
}

Instead of

Scanner scnr = new Scanner(System.in); 

int number = 0;
int validNum = 0;

number = scnr.nextInt();  

if (((number >= 4) && (number <=10))) 
{
   validNum = number;
}
like image 339
Anonymous Avatar asked Nov 23 '16 05:11

Anonymous


People also ask

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. For example if we want to check whether the input is a valid integer we can use the hasNextInt() method.

How do you check if an input is a number in Java with Scanner?

Validate integer input using Scanner in Java We can use hasNextInt() method to check whether the input is integer and then get that using nextInt() method.

What happens when a non integer is read by a nextInt ()?

Because nextInt() will try to read the incoming input. It will see that this input is not an integer, and will throw the exception. However, the input is not cleared.


2 Answers

You can use hasNext(String pattern)

Main:

import java.util.Scanner;

public class Test
{

    public static void main ( String [ ] args )
    {
        System.out.print ( "Enter number: " );
        Scanner scnr = new Scanner(System.in); 

        int number = 0;
        //Check number within range 4-10
        if (scnr.hasNext ( "^[4-9]|10" )) 
        {
           number = scnr.nextInt();
           System.out.println ( "Good Number: " + number );
        }
        else{
            System.out.println ( "Is not number or not in range" );
        }

    }
}

Tests:

Enter number: 3
Is not number or not in range
Enter number: 4
Good Number: 4
Enter number: 10
Good Number: 10
Enter number: 11
Is not number or not in range
like image 130
Rcordoval Avatar answered Oct 19 '22 06:10

Rcordoval


nextInt() will return new number on each call, so you can't do this

like image 31
Oleg Antonyan Avatar answered Oct 19 '22 06:10

Oleg Antonyan