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

时间:2016-11-23 05:05:29

标签: java if-statement java.util.scanner

目的是减少变量的数量,而不是制作许多变量,我想做这样的事情:

Scanner scnr = new Scanner(System.in); 

int number = 0;

scnr.nextInt();  

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

而不是

Scanner scnr = new Scanner(System.in); 

int number = 0;
int validNum = 0;

number = scnr.nextInt();  

if (((number >= 4) && (number <=10))) 
{
   validNum = number;
}

3 个答案:

答案 0 :(得分:4)

nextInt()会在每次通话时返回新号码,因此您无法执行此操作

答案 1 :(得分:4)

您可以使用hasNext(String pattern)

主:

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

    }
}

试验:

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 :(得分:0)

我很想在 do-while 循环中嵌入条件:

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

scnr.nextInt();  

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

虽然我是 Java 新手,但仍然对扫描仪缓冲区中剩余的内容有一些疑问,nextInt() 方法会解析该行,直到找到一个整数但不返回 \n 或其他任何内容,据我目前所知。