使用Java验证输入

时间:2014-02-19 21:28:24

标签: java validation

我是个菜鸟,所以如果我问一个愚蠢的问题,我道歉。我要求用户输入数值。如果值小于12,或者是非数字值,例如数字,我希望它提示它们进行另一个输入。输入值至少为12时,我希望将该值分配给名为creditUnits的变量;

当我要求初始提示时,如果输入的值是非数字,我的程序将捕获它,它将要求用户“输入有效数字:”。 while循环似乎运行良好。

我遇到了第二个循环的问题,它应该捕获少于12的任何输入的数字。它会要求用户输入一个大于11的值。我遇到的问题是这一点,如果用户此时输入任何值,程序就在那里。任何帮助将不胜感激,我提前为我的代码的粗糙道歉:

System.out.print("Enter the credits's you will take each term: ");

while (!in.hasNextDouble()){
    System.out.print("Enter a valid number: ");
    in.next();
}

creditUnits = in.nextDouble();

if (creditUnits < 12){
    System.out.print("Enter a number greater than 11: ");
    in.next();
}

creditUnits = in.nextDouble();                       
System.out.println("You will be taking " + creditUnits + " credits per term.");    

2 个答案:

答案 0 :(得分:4)

这是因为当你只想要第一个输入时,你要求扫描仪抓住下两个输入。

System.out.print("Enter the credits's you will take each term: ");

while (!in.hasNextDouble()){
    System.out.print("Enter a valid number: ");
    in.next();
}

creditUnits = in.nextDouble();

if (creditUnits < 12){
        System.out.print("Enter a number greater than 11: ");
        creditUnits = in.nextDouble();  
}


System.out.println("You will be taking " + creditUnits + " credits per term.")

另外,您应该考虑的一件事是将if(creditUnits < 12)块放在while循环中,这样您就可以不断检查它们是否输入了大于12的数字。

类似的东西:

System.out.print("Enter the credits's you will take each term: ");
while (true){
    System.out.print("Enter a valid number: ");
    creditUnits = in.nextDouble();
    if (creditUnits < 12){
        System.out.print("\nNumber must be greater than 12!\n"); 
    }else
        break;
}

System.out.println("You will be taking " + creditUnits + " credits per term.");

另外,也没有愚蠢的问题。只有愚蠢的传单粉丝。 /笑话

答案 1 :(得分:0)

像陷入困境的Swag说的那样,

if (creditUnits < 12){
    System.out.print("Enter a number greater than 11: ");
    in.next();
}

in.next()会丢掉你输入的内容。然后,如果只输入空格,扫描器会阻塞,直到它在这里输入一倍:

creditUnits = in.nextDouble();

如果你输入除了空格之外的任何其他内容(我假设你只是按进入)那么它将打印出“你将要采取...”部分,如果它是一个有效的双倍。否则会抛出InputMismatchException。

您可能最好手动接收输入并应用有效性检查,而不是循环nextDouble

public static void main(String[] args) throws IOException {
    System.out.print("Enter the credits you will take each term: ");

    Scanner in = new Scanner(System.in);
    String input = in.next();

    double credits = 0.0;

    while (true) {
        try {
            credits = Double.parseDouble(input);
            if (credits < 12.0) {
                throw new IllegalArgumentException("Must take at least 12 credits.");
            } else {
                break;
            }
        } catch(IllegalArgumentException e) {
            System.out.print("Enter a number greater than 11: ");
            input = in.next();
        }
    }

    System.out.println("You will be taking " + credits + " credits per term.");
    in.close();
}