java - 如果用户输入数字而不是字符串,JAVA如何编写异常?
问题描述
请解释一下我对 do while 有点困惑。如果我第一次输入城市名称,一切正常。但是如果我输入一个数字,我会收到相应的消息,当我第二次尝试输入城市名称时,它会给出相同的消息.(关于无效数据)
String town=scanner.nextLine();
boolean tryagain = false;
do {
if (town.charAt(0) >= '0' && town.charAt(0) <= '9'){
System.out.println("You probably entered an invalid data format");
scanner.nextLine();
tryagain = true;}
else {
tryagain = false;
}
}while (tryagain);
我也尝试了 try and catch 选项,但如果用户输入数字而不是字符串,我无法编写异常。它不起作用。请帮忙。
try {
System.out.println("enter the name of the city");
town = scanner.nextLine();
} catch (InputMismatchException e) {
System.out.println ("You probably entered an invalid data format ");
scanner.nextLine();
}
解决方案
将其放在 try 块中并尝试将其解析为 Integer
try{
Integer.parseInt(town)
}catch(NumberFormatException nfe){
//this is a string otherwise it would be number
}
推荐阅读
- ssl - AWS Linux 2 - 让我们加密多域
- python - 如何找到 SkLearn 模型的 LSA 和 LDA 的连贯性分数?
- javascript - 在 SuiteScript 中发送带有正确回复的案例回复电子邮件
- teradata - 查询以确定比正常短的列值
- sql - 如何在 SAS Proc SQL 中建立只读“连接到 ODBC”连接?
- powerbi - 从历史数据中得出方差并将其应用于未来预测——Power BI
- sql - 数组上的 Postgresql ARRAY_AGG 仅返回第一个值
- sql - 将存储过程转换为函数
- pine-script - 为什么转换后的 think script 代码不起作用?
- javascript - 元素值属性与控件内容不匹配?