【问题标题】:How can I make the code catch the error when the input provided is not a number?当提供的输入不是数字时,如何使代码捕获错误?
【发布时间】:2019-06-10 09:17:34
【问题描述】:

程序检查用户输入并确定它是正面的还是负面的。 当用户提供无效输入(非整数)(例如“444h”或“ibi”)时,如何捕获错误。

我在想最后的 else 语句会捕获异常,但它没有。

import java.util.Scanner;
public class Demo

{

    public static void main(String[] args)
    {

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter any number: ");

        int num = scan.nextInt();

        scan.close();
        if(num > 0)
        {
            System.out.println(num+" is positive");
        }
        else if(num < 0)
        {
            System.out.println(num+" is negative");
        }
        else if(num == 0)
        {
            System.out.println(num+" is neither positive nor negative");
        }
        else
        {
            System.out.println(num+" must be an integer");
        }
    }
}

我希望程序能够捕获异常并提示输入有效整数

【问题讨论】:

  • nextInt 只消耗 int 值
  • 您是否阅读了nextInt() 的文档?你知道java异常处理吗,try/catch

标签: java


【解决方案1】:

只需将您的代码包装在 try..catch block 中。

完整代码:

import java.util.Scanner;
import java.util.InputMismatchException;

class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter any number: ");

        try {
            int num = scan.nextInt();
            if (num > 0) {
                System.out.println(num + " is positive");
            } else if (num < 0) {
                System.out.println(num + " is negative");
            } else if (num == 0) {
                System.out.println(num + " is neither positive nor negative");
            }
        } catch (InputMismatchException e) {
            System.out.println("Error: Value Must be an integer");
        }

        scan.close();
    }
}

祝你好运:)

【讨论】:

    【解决方案2】:
    int num = 0;
        try{
            num =input.nextInt();
        }catch(InputMismatchException ex) {
            System.out.println("Enter Integer Value Only");
        }
    

    如果您从输入中获得非整数值,则必须在 try 块中编写 int num = scan.nextInt(); 这条语句,然后 InputMismatchException 将出现然后执行 catch 块。

    【讨论】:

      【解决方案3】:

      首先,如果您打算在应用程序运行期间再次使用扫描仪,请不要关闭它。关闭它后,您需要重新启动应用程序才能再次使用它。

      如前所述,您可以在 Scanner#nextInt() 方法上使用 try/catch

      Scanner scan = new Scanner(System.in);
      
      int num = 0;
      boolean isValid = false;
      while (!isValid) {
          System.out.print("Enter any number: ");
          try {
              num = scan.nextInt();
              isValid = true;
          }
          catch (InputMismatchException ex) {
              System.out.println("You must supply a integer value");
              isValid = false;
              scan.nextLine(); // Empty buffer
          }
      }
      
      if (num > 0) {
          System.out.println(num + " is positive");
      }
      
      else if (num < 0) {
          System.out.println(num + " is negative");
      }
      
      else if (num == 0) {
          System.out.println(num + " is neither positive nor negative");
      }
      

      或者你可以使用 Scanner#nextLine() 方法来代替它接受字符串:

      Scanner scan = new Scanner(System.in);
      
      String strgNum = "";
      boolean isValid = false;
      while (!isValid) {
          System.out.print("Enter any Integer value: ");
          strgNum = scan.nextLine();
      
          /* See if a signed or unsigned integer value was supplied.
             RegEx is used with the String#matches() method for this.
             Use this RegEx: "-?\\d+(\\.\\d+)?"  if you want to allow
             the User to enter a signed or unsigned Integer, Long, 
             float, or double values.         */
          if (!strgNum.matches("-?\\d+")) {
              System.out.println("You must supply a numerical value (no alpha characters allowed)!");
              continue;
          }
          isValid = true; // set to true so as to exit loop
      }
      int num = Integer.parseInt(strgNum); // Convert string numerical value to Integer
      /* Uncomment the below line if you use the other RegEx. You would have to also 
         comment out the above line as well.   */
      // double num = Double.parseDouble(strgNum); // Convert string numerical value to double
      if (num > 0) {
          System.out.println(num + " is positive");
      }
      else if (num < 0) {
          System.out.println(num + " is negative");
      }
      else if (num == 0) {
          System.out.println(num + " is neither positive nor negative");
      }
      

      【讨论】:

        【解决方案4】:

        使用正则表达式检查输入是否为数字

        import java.util.regex.*;
        Pattern.matches("[0-9]+", "123"); // this will return a boolean
        

        【讨论】:

        • 这假设如何使用 Scanner#nextInt() 工作?
        猜你喜欢
        • 2021-02-05
        • 2021-05-27
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 2015-12-23
        • 1970-01-01
        • 1970-01-01
        • 2011-12-05
        相关资源
        最近更新 更多