Titanic Lover Titanic Lover - 16 days ago 6
Java Question

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 = scnr.nextInt();
}

Answer

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