Anonymous
Anonymous

Reputation: 499

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;
}

Upvotes: 8

Views: 849

Answers (3)

jfo420
jfo420

Reputation: 11

I would be tempted to embed the condition within a do-while loop:

Scanner scnr = new Scanner(System.in); 
int number = 0;

scnr.nextInt();  

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

I am new to java though, and still have some doubts about what is left in the scanner buffer, the nextInt() method parses the line until it finds an integer but is not returning the \n, or whatever it may be, as of I understood so far.

Upvotes: 0

Oleg Antonyan
Oleg Antonyan

Reputation: 3123

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

Upvotes: 4

rodridevops
rodridevops

Reputation: 1997

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

Upvotes: 5

Related Questions