在if语句WITHOUT变量中验证扫描仪用户输入

时间:2022-03-08 23:10:46

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

2 个解决方案

#1


4  

You can use hasNext(String pattern)

你可以使用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

#2


4  

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

nextInt()将在每次调用时返回新的数字,因此您无法执行此操作

#1


4  

You can use hasNext(String pattern)

你可以使用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

#2


4  

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

nextInt()将在每次调用时返回新的数字,因此您无法执行此操作