[英]Java Scanner not accepting integer input before string
public static void main(String[] args) {
Student[] test = new Student[7];
for (int i = 0; i < 7; i++) {
test[i] = new Student();
Scanner kb = new Scanner(System.in);
System.out.println("What is the Students ID number?: ");
test[i].setStudentId(kb.nextInt());
System.out.println("What is the Students name?: ");
test[i].setStudentName(kb.nextLine());
}
}
在上面的程序中,當我首先嘗試取整數輸入時它會跳過字符串輸入,但在同一個程序中,如果我首先保持字符串輸入,它可以正常工作。 這背后可能是什么原因?
Scanner kb = new Scanner(System.in);
System.out.println("What is the Students name?: ");
test[i].setStudentName(kb.nextLine());
System.out.println("What is the Students ID number?: ");
test[i].setStudentId(kb.nextInt());
該計划的輸出將是
什么是學生證號碼?:1
什么是學生姓名?://我不會讓我在這里輸入字符串
什么是學生證號碼?:
但是當我在字符串上方輸入Integer時,它運行正常。 可能是什么原因?
對nextInt()
的調用只讀取整數,行分隔符( \\n
)保留在緩沖區中,因此后續對nextLine()
調用只會讀取,直到行分隔符已存在。 解決方案是使用nextLine()
作為ID,然后使用Integer.parseInt(kb.nextLine())
將其解析為整數。
在調用nextInt()
,掃描程序已超過整數,但未超過輸入整數的行的末尾。 當您嘗試讀取ID字符串時,它會讀取行的其余部分(空白)而不等待進一步的輸入。
要解決此問題,只需在調用nextInt()
之后添加對nextLine()
調用。
System.out.println("What is the Students ID number?: ");
test[i].setStudentId(kb.nextInt());
kb.nextLine(); // eat the line terminator
System.out.println("What is the Students name?: ");
test[i].setStudentName(kb.nextLine());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.