Java 如何使用扫描仪检查用户输入是否为整数?

Java 如何使用扫描仪检查用户输入是否为整数?,java,input,integer,java.util.scanner,Java,Input,Integer,Java.util.scanner,我希望国家代码是由用户输入的整数。我希望在用户输入非整数代码时显示错误消息。我该怎么做?该程序要求用户输入国家名称和国家代码。用户将在其中输入国家代码。但若用户输入一个字符,我希望显示一条消息,说明输入无效 System.out.println("Enter country name:"); countryName = in.nextLine(); System.out.println("Enter country code:");

我希望国家代码是由用户输入的整数。我希望在用户输入非整数代码时显示错误消息。我该怎么做?该程序要求用户输入国家名称和国家代码。用户将在其中输入国家代码。但若用户输入一个字符,我希望显示一条消息,说明输入无效

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

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

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");
}
如果输入不是int值,则Scanner的nextInt look for API方法抛出,您可以捕获该方法,然后要求用户再次输入“国家代码”,如下所示:

  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
  }
您可以检查hasNextInt,然后致电nextInt


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

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());
        }

如果您正在创建自己的自定义异常类,则使用regex检查输入字符串是否为整数

私有最终字符串regex=[0-9]

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

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

如果不创建自定义异常处理程序,则可以使用内置InputMismatchException。

为什么新的ScannerSystem.in在while循环中?是的,无需,已修复。请阅读以了解情况
if (codeNumber.matches(regex)) {
    // do stuff.
} else {
    throw new InputMismatchException(codeNumber);
}