首页 > 解决方案 > 检测输入字符串与整数的异常处理

问题描述

如果一行中的第二个输入是字符串而不是整数,我需要编写程序失败并引发异常的代码。我对如何比较输入是字符串还是 int 感到困惑,而且我也在努力研究如何使用 try/catch 语句。

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

public class NameAgeChecker {
public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);

  String inputName;
  int age;
  
  inputName = scnr.next();
  while (!inputName.equals("-1")) {
     // FIXME: The following line will throw an InputMismatchException.
     //        Insert a try/catch statement to catch the exception.
     age = scnr.nextInt();
     System.out.println(inputName + " " + (age + 1));
     
     inputName = scnr.next();
  }

}

标签: java

解决方案


代替

age = scnr.nextInt();

尝试

try {
    age = scnr.nextInt();
    System.out.println(inputName + " " + (age + 1));
}
catch(InputMismatchException e) {
    System.out.println("Please enter a valid integer");
}

推荐阅读