【问题标题】:check if integer is inputted in java and not string [closed]检查是否在java中输入整数而不是字符串[关闭]
【发布时间】:2013-06-18 14:17:45
【问题描述】:

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

    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){
        }
    }

【问题讨论】:

  • 将其移出while 循环,最好在...之前...
  • 我需要再次询问该问题,以便用户能够提出另一个答案,所以我做了一个循环
  • 变量'input'的类型是什么?
  • 那么你的代码有问题,这里没有显示。
  • 为什么不使用if(input.hasNextInt()) 来了解用户是否输入了数字而不是try-catch 块?

标签: java string input integer


【解决方案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】:

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

    因为它第二次进入其他条件

    【讨论】:

    • 如果代码通过else 条件,它不会再次打印消息...
    • 是的,我想告诉你。
    • 看起来 OP 在欺骗我们,或者他/她并不真正了解编程(请参阅已接受的答案)...
    【解决方案3】:

    由于用户的输入,打印了两次,如果原因如下,请尝试将消息放入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){
        }
    }
    

    【讨论】:

      【解决方案4】:

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

         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){
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-18
        • 1970-01-01
        相关资源
        最近更新 更多