java - 检测输入字符串与整数的异常处理
问题描述
如果一行中的第二个输入是字符串而不是整数,我需要编写程序失败并引发异常的代码。我对如何比较输入是字符串还是 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();
}
}
解决方案
代替
age = scnr.nextInt();
尝试
try {
age = scnr.nextInt();
System.out.println(inputName + " " + (age + 1));
}
catch(InputMismatchException e) {
System.out.println("Please enter a valid integer");
}
推荐阅读
- python - Django DEBUG 在幕后做了什么?
- python-3.x - 运行 RandomizedSearchCV 为大数据调整 LightGBM Regressor
- python - 使用 Panda Read SQL 的 SQL 查询绑定数不正确
- spring - 如何在 testpropertysource 附加属性中获取 SpringBootTest.WebEnvironment.RANDOM_PORT?
- java - 带有停用词的 Solr 短语查询
- angular - Angular NgRx 效果不会触发
- python - Python通过函数发送每个字符?
- sql - 从 installshield 运行 SQL 语句时出现语言问题
- python - 如何通过在python中逐行解析来获取文件中的所有id
- java - org.apache.camel.impl.HeaderFilterStrategyComponent 类型无法解析