[英]Putting a loop around nested if else statements
我在使用Java方面有點新。 我正在開發一個程序,其中包含學生姓名及其ID,然后輸入正確的ID后,它會吐出該學生的信息。 示例輸出看起來像這樣:您想輸入多少個學生? (2)他們叫什么名字? (薩莉,傑克)他們的ID是什么? (2332,5631)您想搜索學生嗎? (Y)請輸入他們的ID:(2332)我們找到了Sally!
這是搜索學生的代碼的片段:
System.out.println("Would you like to search for a student?");
String answer = scan.next();
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
int id = scan.nextInt();
boolean found = Student.lookupID(list, id);
if(found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); //fix this
else
System.out.println("Error");
}
else {
System.out.println("Thanks for using this system!");
}
}
}
現在,我正在嘗試循環代碼,以便輸出現在看起來像這樣:您想輸入多少個學生? (3)他們叫什么名字? (Sally,Jack,Rick)他們的ID是什么? (2332,5631,3005)您想搜索學生嗎? (Y)請輸入他們的ID:(2332)我們找到了Sally! 您想尋找另一個學生嗎? (Y)請輸入他們的ID:(5631)我們找到了傑克! 您想尋找另一個學生嗎? (N)感謝您使用我們的系統!
有人可以幫助我嗎?
您需要重置ID以使程序能夠獲取新ID。嘗試像這樣更正您的代碼:
System.out.println("Would you like to search for a student?");
String answer = scan.next();
int id = 0; //RESET THE ID TO BE ABLE REPLAYIN WORK!
if (answer.equals("Y")) {
System.out.println("Please enter an ID:");
id = scan.nextInt();
boolean found = Student.lookupID(id);
if (found)
System.out.println("Student was found. This student is: " + studentName + ", Student ID " + id); // fix
// this
else
System.out.println("Error");
} else {
System.out.println("Thanks for using this system!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.