3 回答
TA貢獻1836條經驗 獲得超13個贊
這個問題是由于nextInt()方法造成的。
這里發生的是該nextInt()方法使用用戶輸入的整數,而不是用戶輸入末尾的換行符,這是在您按下enter鍵時創建的。
enter因此,當您在輸入整數后按下時,下一次調用會nextLine()消耗新的換行符,該換行符在循環的最后一次迭代中沒有消耗nextInt()。這就是為什么它String在循環的下一次迭代中跳過輸入并且不等待用戶輸入String
解決方案
nextLine()您可以通過在調用后nextInt()調用來消耗換行符
for(i = 0; i < n; i++)
{
System.out.println("Enter String" + (i + 1) + ":");
sentence[i] = scan.nextLine();
System.out.printf("Enter int " + (i + 1) + ":");
numbers[i] = scan.nextInt();
scan.nextLine(); // <------ this call will consume the new line character
}
TA貢獻1829條經驗 獲得超7個贊
像這樣放置 scan.nextLine() :
for(i = 0; i < n; i++){
System.out.println("Enter String" + (i + 1) + ":");
sentence[i] = scan.nextLine();
System.out.printf("Enter int " + (i + 1) + ":");
numbers[i] = scan.nextInt();
scan.nextLine();
}
TA貢獻1847條經驗 獲得超7個贊
使用 sc.next(); 而不是 sc.nextLine(); 如果無法在第一次迭代中輸入字符串值。
Scanner sc = new Scanner(System.in);
for(i = 0; i < n; i++);
System.out.println("Enter String" + (i + 1) + ":");
sentence[i] = sc.next();
System.out.printf("Enter int " + (i + 1) + ":");
numbers[i] = sc.nextInt();
sc.nextLine();
}
添加回答
舉報
