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();
}
添加回答
举报
