[英]Program asks the same response twice?
My Student Records 程序要求用戶在 do while 循環中輸入一次學生的名字。 用戶可以選擇通過輸入 yes 再次輸入相同的數據,並且相同的問題“輸入學生的名字:”出現兩次,一個在另一個之上。
我在那個 while 循環中插入了斷點,一旦用戶在 do 結束時選擇“是”,它就會上升到第一個 while 循環中的第一行,然后是第二行、第三行,然后又回到第一行,然后是第二個,第三個,然后進入下一個 while 循環,詢問學生的姓氏。
為什么我的程序在 do while 循環的第二次將第一個問題吐兩次?
package assignment_3;
import java.util.Scanner;
/**
* @author Diego
*/
public class Demo {
public static void main (String args[]) {
//Instantiating new recordsObject
StudentRecords recordsObject = new StudentRecords();
String firstName = "";
String lastName = "";
String idNumber = "";
String major = "";
Scanner keyboard = new Scanner(System.in);
//Asking the user to enter the students' info
do {
while ( firstName.isEmpty() ) {
System.out.println("Enter student's first name: ");
firstName = keyboard.nextLine();
}
while ( lastName.isEmpty() ) {
System.out.println("Enter student's last name: ");
lastName = keyboard.nextLine();
}
while ( idNumber.length() != 9 ) {
System.out.println("Enter student's nine-digit ID#: ");
idNumber = keyboard.nextLine();
}
while ( major.isEmpty() ) {
System.out.println("Enter student's major: ");
major = keyboard.nextLine();
}
//Concatinating first name and last name into name
String name = firstName + " " + lastName;
//Adding the new entry to the StudentArrayList
StudentEntry entry = new StudentEntry (name ,idNumber, major);
recordsObject.addStudentEntry (entry);
//Resetting variables
firstName = "";
lastName = "";
idNumber = "";
major = "";
/*If the user enters "yes" then they can submit more.
If they enter "no", then all submitted info will be shown */
System.out.println("Type yes to add another entry");
} while (keyboard.next().equalsIgnoreCase("YES"));
keyboard.close();
//Printing out those entries
System.out.println("Student Records");
System.out.println("---------------");
for (int index = 0 ; index < recordsObject.StudentArrayList.size() ; index++) {
System.out.println(recordsObject.StudentArrayList.get(index));
System.out.println("");
}
}
}
該問題是由在主 while 循環中使用 keyboard.next() 引起的。 Next 不讀取換行符。 因此,當用戶鍵入“yes”時,讀取下一個 firstName 的代碼將自動讀取剩余的換行符,仍然將 firstName 保留為空。 而且,由於 firstName 仍然為空,它會再次提示。
改變:
} while (keyboard.next().equalsIgnoreCase("YES"));
至:
} while (keyboard.nextLine().equalsIgnoreCase("YES"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.