【问题标题】:Possible exception if User enters String instead of Int如果用户输入 String 而不是 Int,则可能出现异常
【发布时间】:2012-10-02 01:06:12
【问题描述】:

我只是在玩 Java。我试图强制我的程序只接受 3 位数字。 我相信我已经使用 while 循环成功地做到了这一点(如果我错了,请纠正我)。 但是如果用户输入一个字符串,我该如何去打印一个错误语句。例如:“abc”。

我的代码:

    import java.util.Scanner;
    public class DigitSum {

    public static void main(String[] args) {

    Scanner newScan = new Scanner(System.in);

        System.out.println("Enter a 3 digit number: ");
        int digit = newScan.nextInt();

        while(digit > 1000 || digit < 100)
            {           
             System.out.println("Error! Please enter a 3 digit number: ");
             digit = newScan.nextInt();
            }

        System.out.println(digit);
       }
    }

【问题讨论】:

    标签: java string loops while-loop int


    【解决方案1】:

    这个怎么样?

    public class Sample {
        public static void main (String[] args) {
            Scanner newScan = new Scanner (System.in);
    
            System.out.println ("Enter a 3 digit number: ");
            String line = newScan.nextLine ();
            int digit;
            while (true) {
                if (line.length () == 3) {
                    try {
                        digit = Integer.parseInt (line);
                        break;
                    }
                    catch (NumberFormatException e) {
                        // do nothing.
                    }
                }
    
                System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
                line = newScan.nextLine ();
            }
    
            System.out.println (digit);
        }
    }
    

    正则表达式版本:

    public class Sample {
        public static void main (String[] args) {
            Scanner newScan = new Scanner (System.in);
    
            System.out.println ("Enter a 3 digit number: ");
            String line = newScan.nextLine ();
            int digit;
    
            while (true) {
                if (Pattern.matches ("\\d{3}+", line)) {
                    digit = Integer.parseInt (line);
                    break;
                }
    
                System.out.println ("Error!(" + line + ") Please enter a 3 digit number: ");
                line = newScan.nextLine ();
            }
    
            System.out.println (digit);
        }
    }
    

    【讨论】:

    • 这是完美的。非常感谢。这正是我想要达到的目标。不过还是谢谢大家。你所有的答案都是有效的。不过,这个对我来说效果更好:D
    • "Integer.parseInt()" 不是本质。您可以使用正则表达式代替“Integer.parseInt()”。
    • 看看你的回答 Ruzia,你用了Integer.parseInt() 我认为这很重要(不管那是什么意思)。另外,考虑到您接受了我的答案,为什么要否决我的答案?
    • 我是谁?我没有对任何人投反对票。我只了解 Integer.parseInt()。不知道正则表达式是什么意思...
    • > JonH 我认为本质是 while 循环代码。 “Integer.parseInt()”是选项之一。
    【解决方案2】:

    在 try catch 块中嵌入读取 int 的代码,每当输入错误的输入时,它将生成异常,然后在 catch 块中显示您想要的任何消息

    【讨论】:

      【解决方案3】:

      如果输入错误,nextInt 方法本身会抛出 InputMismatchException

      try {
        digit = newScan.nextInt() 
      } catch (InputMismatchException e) {
        e.printStackTrace();
        System.err.println("Entered value is not an integer");
      }
      

      应该这样做。

      【讨论】:

        【解决方案4】:

        我会如何使用 if 语句。 if 语句应该是这样的:

        if(input.hasNextInt()){
            // code that you want executed if the input is an integer goes in here    
        } else {
           System.out.println ("Error message goes here. Here you can tell them that you want them to enter an integer and not a string.");
        }
        

        注意:如果您希望他们输入字符串而不是整数,请更改 if 声明到 input.hasNextLine() 而不是 input.hasNextInt()

        第二个注意事项:input 是我为我的扫描仪命名的。如果你命名你的煎饼,那么你应该输入pancakes.hasNextInt()pancakes.hasNextLine()

        希望我能帮上忙,祝你好运!

        【讨论】:

          【解决方案5】:

          当您抓取输入或拉取输入字符串时,请运行parseInt。 如果yourString 不是Integer,这实际上会引发异常:

          Integer.parseInt(yourString)

          如果它抛出一个异常,你就知道它不是一个有效的输入,所以此时你可以显示一条错误消息。以下是parseInt 上的文档:

          http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String)

          【讨论】:

          • 这很容易知道。谢谢。
          【解决方案6】:

          您可以通过以下方式检查字符串是否为数值:

          1) 使用 try/Catch 块

          try  
          {  
            double d = Double.parseDouble(str);  
          }catch(NumberFormatException nfe)  {
            System.out.println("error");
          }  
          

          2) 使用正则表达式

          if (!str.matches("-?\\d+(\\.\\d+)?")){
            System.out.println("error");
          }
          

          3) 使用 NumberFormat 类

          NumberFormat formatter = NumberFormat.getInstance();
          ParsePosition pos = new ParsePosition(0);
          formatter.parse(str, pos);
          if(str.length() != pos.getIndex()){
            System.out.println("error");
          }
          

          4) 使用 Char.isDigit()

          for (char c : str.toCharArray())
          {
              if (!Character.isDigit(c)){
                System.out.println("error");
              }
          }
          

          您可以查看How to check if a String is numeric in Java了解更多信息

          【讨论】:

            【解决方案7】:

            如果用户输入诸如 'abc' 之类的字符串而不是 integer 值然后 @987654321,您希望发生 Exception @ 适合你。

            让我给你一个基本的例子。

            public static void main(String[] args)
                {
                    Scanner ip = new Scanner(System.in);
                    int a; 
                    System.out.println("Enter Some Input");
                    try{
                        a = ip.nextInt();
                    }
                    catch(InputMismatchException msg){
                        System.out.println("Input Mismatch Exception has occured " + msg.getMessage());
                    }
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-11-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多