-2

我在下面有一个代码,其中用户必须只输入数字,程序正在运行,但问题是 System.out.println("Mother's Age: ") 在加载过程中被打印了 2 次

    while (count == 0){
        int x;
        System.out.println("Mother's Age: ");
        ans2 = input.nextLine();
        try{
            x = Integer.parseInt(ans2);
            System.out.println(count);                
            if (!(x >= 18 && x <= 45)) {
            }
            else{
                count = 1;
            }
        }
        catch (NumberFormatException nFE){
        }
    }
4

4 回答 4

1

System.out.println("Mother's Age: ");在 while 循环()之后或之前添加Outside loop

因为它第二次进入else 状态

于 2013-06-18T14:24:30.450 回答
1

做这个:

System.out.println("Mother's Age: ");
while (count == 0){
        int x;
        ans2 = input.nextLine();
        try{
            x = Integer.parseInt(ans2);
            System.out.println(count);                
            if (!(x >= 18 && x <= 45)) {
            }
            else{
                count = 1;
            }
        }
        catch (NumberFormatException nFE){
        }
    }
于 2013-06-18T14:31:10.150 回答
0

我从你的帮助中得到了这个,它正在按照我的期望工作,谢谢!

   System.out.println("Mother's Age At Conception(18-45): ");
    while (count == 0){
        int x;
        ans2 = input.nextLine();
        try{
            x = Integer.parseInt(ans2);           
            if (!(x >= 18 && x <= 45)) {
                System.out.println("Invalid Input Please Try Again!");
                System.out.println("Mother's Age At Conception(18-45): ");
            }
            else{
                count = 1;
            }
        }
        catch (NumberFormatException nFE){
        }
    }
于 2013-06-18T14:41:19.103 回答
0

由于用户的输入,它被打印了两次,如果原因如下,请尝试将消息放入 de 中:

 while (count == 0){
    int x;
    System.out.println("Mother's Age: ");
    ans2 = input.nextLine();
    try{
        x = Integer.parseInt(ans2);
        System.out.println(count);                
        if (!(x >= 18 && x <= 45)) {
             System.out.println("Invalid age!!!");
        }
        else{
            count = 1;
        }
    }
    catch (NumberFormatException nFE){
    }
}
于 2013-06-18T14:31:34.383 回答