如何验证来自扫描程序的数据(Java)

时间:2017-10-11 09:51:42

标签: java validation java.util.scanner

我需要让用户输入1到10之间的数字,然后得到这个数字的阶乘,除了验证用户名之外我能做的一切(在范围内&&不是字符串) )

/etc/apt/sources.list

3 个答案:

答案 0 :(得分:-1)

    int userInput = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Please enter a number from 2 to 100");
    while (!sc.hasNextInt()) {
        System.out.println("Please enter number");
        sc.next();
    }
    while(true) {
        userInput = sc.nextInt();
        if (userInput > 2 && userInput < 100) {
            break;
        }else{
            System.out.println("Please enter a number between 2 to 100");
        }
    }
    System.out.println(userInput);

答案 1 :(得分:-1)

或者只是使用do-while

 do {

   userInput = sc.nextInt();

 } while (userInput < 1 || userInput > 10);

答案 2 :(得分:-1)

您可以尝试的一种方法是

public static void main(String[] args) {

int userInput = 0 ;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number from 2 to 100");

while (!sc.hasNextInt())
{
 System.out.println("wrong input");
 sc.next();
}  

if (sc.nextInt() < 101) {
    userInput = sc.nextInt();
}
System.out.println(userInput);

 }
}