【问题标题】:How to check the user input is an integer or not with Scanner?如何使用扫描仪检查用户输入是否为整数?
【发布时间】:2018-02-04 17:09:51
【问题描述】:

我希望国家代码是用户输入的整数。我希望在用户输入不是整数的代码时显示错误消息。我怎样才能做到这一点?该程序要求用户输入国家名称和国家代码。用户将在其中输入国家代码。但是,如果用户输入了一个字符,我希望显示一条消息说输入无效。

System.out.println("Enter country name:");                     
countryName = in.nextLine();
System.out.println("Enter country code:");            
int codeNumber = in.nextInt(); 
in.nextLine();

【问题讨论】:

标签: java input integer java.util.scanner


【解决方案1】:

如果输入的不是int值,那么ScannernextInt()(API看here)方法抛出InputMismatchException,你可以catch然后要求用户重新- 再次输入“国家代码”,如下图:

  Scanner in = new Scanner(System.in);
  boolean isNumeric = false;//This will be set to true when numeric val entered
  while(!isNumeric)
     try {
        System.out.println("Enter country code:");
        int codeNumber = in.nextInt(); 
        in.nextLine();
        isNumeric = true;//numeric value entered, so break the while loop
        System.out.println("codeNumber ::"+codeNumber);
  } catch(InputMismatchException ime) {
     //Display Error message
     System.out.println("Invalid character found,
            Please enter numeric values only !!");
     in.nextLine();//Advance the scanner
  }

【讨论】:

  • 为什么new Scanner(System.in)在while循环里面?
  • 是的,不需要,修复它
【解决方案2】:

一种简单的方法是,像读取名称一样读取数字行,然后使用 Regex(正则表达式)检查是否仅包含数字,使用字符串匹配方法 codeNumber.matches("\\d+") ,如果为假,则返回布尔值,则它不是数字,您可以打印错误消息。

System.out.println("Enter country name:");                     
countryName = in.nextLine();
System.out.println("Enter country code:");            
String codeNumber = in.nextLine(); 
if (codeNumber.matches("\\d+")){
    // is a number
} else {
    System.out.println("Please, inform only numbers");
}

【讨论】:

    【解决方案3】:

    您可以这样做,首先将输入作为字符串获取,然后尝试将字符串转换为整数,如果不能,则输出错误消息:

    String code= in.nextLine();
    try
            {
              // the String to int conversion happens here
              int codeNumber = Integer.parseInt(code);
            }
    catch (NumberFormatException nfe)
            {
              System.out.println("Invalid Input. NumberFormatException: " + nfe.getMessage());
            }
    

    【讨论】:

      【解决方案4】:

      您可以改为检查hasNextInt,然后致电nextInt

      int codeNumber;
      
      System.out.println("Enter country code:");
      
      if(in.hasNextInt())
      {
          codeNumber = in.nextInt();
      }
      else
      {
          System.out.println("Invalid Code !!");
      }
      

      【讨论】:

        【解决方案5】:

        如果您要创建自己的自定义异常类,请使用正则表达式检查输入字符串是否为整数。

        private final String regex = "[0-9]";

        然后,检查输入是否遵循正则表达式模式。

        if (codeNumber.matches(regex)) {
            // do stuff.
        } else {
            throw new InputMismatchException(codeNumber);
        }
        

        如果您不创建自定义异常处理程序,则可以在 InputMismatchException 中使用 build。

        【讨论】:

          猜你喜欢
          • 2014-05-11
          • 2023-03-17
          • 1970-01-01
          • 2013-11-26
          • 1970-01-01
          • 1970-01-01
          • 2010-09-11
          • 2021-05-14
          • 1970-01-01
          相关资源
          最近更新 更多