检查是否在java中输入了整数而不是字符串

时间:2013-06-18 14:17:45

标签: java string input integer

我有一个代码,其中用户必须只输入数字,程序正在运行但问题是System.out.println(“母亲的年龄:”)在加载过程中被打印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 个答案:

答案 0 :(得分:1)

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

因为它第二次进入 else条件

答案 1 :(得分: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){
        }
    }

答案 2 :(得分: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){
    }
}

答案 3 :(得分: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){
        }
    }