1 回答

TA貢獻(xiàn)1851條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果出現(xiàn)錯(cuò)誤,您需要循環(huán)返回。在布爾變量和簡(jiǎn)單的 while 循環(huán)的幫助下,應(yīng)該沒(méi)問(wèn)題。
像這樣的東西:
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);
您也可以消除該變量。通過(guò)做類(lèi)似的事情:
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");
}
}
編輯:支持或多個(gè)字段。
// 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");
}
}
添加回答
舉報(bào)