[英]Scanner using with while loop and switch statement
我正在用Java創建一個簡單的控制台應用程序,但遇到了麻煩。 這是我的代碼:
boolean isActive = true;
Scanner scanner = new Scanner(System.in);
do {
try {
int option = scanner.nextInt();
switch (option) {
case 1:
System.out.println("Search By Registration number: " +
"\n------------------------------");
System.out.println("Enter registration number!");
String regNumber = scanner.nextLine();
if (regNumber == incorrect) {
continue; // return to case 1 and ask enter regnumber one more time
} else {
// do stuff
}
break;
case 2:
System.out.println("Exit the search option: ");
isActive = false;
break;
default:
System.out.println("Your selection was wrong. Try one more time!");
break;
}
} catch (InputMismatchException ex) {
System.out.println("Your selection was wrong. Try one more time!");
}
scanner.nextLine();
} while (isActive);
如果發生錯誤,我將無法返回案例1。 因此,如果發生錯誤,用戶必須獲得消息“關於再次輸入注冊號”,依此類推。
檢查regNumber時需要使用equals()
if (regNumber.equals(incorrect)) {
System.out.println("Incorrect!");
continue;
} else {
System.out.println("Correct!");
}
但是即使這樣,您的程序仍無法正常運行,請在此上更改String regNumber = Scanner.nextLine() :
String regNumber = scanner.next();
您可以在regNumber的輸入周圍放一個循環,以偵聽不正確的輸入。
String regNumber = incorrect;
// String is a reference type, therefore equality with another String's value
// must be checked with the equals() method
while(regNumber.equals(incorrect)){
if (regNumber.equals(correct)) {
// Do something if input is correct
}
}
這可能不是您想要的確切解決方案,但是請考慮相同的概念並將其應用於您的程序。 另請參閱此以獲取有關字符串比較的更多信息。 希望這對您有所幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.