【发布时间】:2020-07-13 15:33:19
【问题描述】:
我想在循环中创建一个 try-catch 块,让用户有多个机会以正确的格式输入信息。当我输入格式不正确的内容时,程序会显示 sysout 消息“请输入格式正确的姓名和年龄”。来自 catch 块。
问题是当我在此消息之后输入格式正确的信息时,它一直显示相同的消息“请以正确的格式输入姓名和年龄”。即使它应该退出并询问我是否要继续。
这是我所拥有的:
int inAge;
String inName;
while (true) {
try {
inAge = Integer.parseInt((input.substring((input.indexOf(',') + 1))));
inName = input.substring(0, input.indexOf(','));
list.add(new Plant(inName, inAge));
break;
} catch (Exception e) {
System.out.println("Please enter name and age with correct format.");
in.next();
}
}
System.out.println("Do you wish to continue? (Yes or No)");
endOrNo = in.nextLine();
if ("yes".equalsIgnoreCase(endOrNo))
go = true;
else
go = false;
【问题讨论】:
标签: java loops try-catch user-input