【发布时间】:2021-11-14 21:54:53
【问题描述】:
请解释一下我对 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();
}
【问题讨论】: