1 回答
TA贡献1851条经验 获得超4个赞
如果出现错误,您需要循环返回。在布尔变量和简单的 while 循环的帮助下,应该没问题。
像这样的东西:
boolean flag = true;
do {
String name = scan.nextLine();
if (name.startsWith("Ms. ") || name.startsWith("Mr. ")) {
System.out.println("Welcome : " + name);
// break the loop.
flag = false;
} else {
System.out.println("Please re-enter your name");
}
} while (flag);
您也可以消除该变量。通过做类似的事情:
while (true) {
String name = scan.nextLine();
if (name.startsWith("Ms. ") || name.startsWith("Mr. ")) {
System.out.println("Welcome : " + name);
break;
} else {
System.out.println("Please re-enter your name");
}
}
编辑:支持或多个字段。
// previous while loop here
flag = true; // resetting flag
while (flag) {
System.out.println("Where do you live? [Contains 'Street']");
String address = scan.nextLine();
if (address.contains("Street")) {
System.out.println("Proceed to the next step");
// terminate the loop
flag = false;
} else {
System.out.println("Please re-enter your address");
}
}
添加回答
举报