我们都知道使用方法input.nextLine()会在运行程序时为字符串提供空格,但是..当我在循环中使用此方法时,运行会跳过该语句。任何人都可以解释原因吗?
我正在尝试菜单:
代码:
do {
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 4:
System.out.println("Please give the full information of the project ");
System.out.print("Project code: "); int code = input.nextInt();
System.out.print("Project Title: "); String title = input.nextLine();
System.out.print("Project Bonus in Percent: "); double bip = input.nextDouble();
Project proj4 = new Project(code4,title4,bip4);
System.out.print("Employee ID you're adding project to: "); String id4=input.next();
ers.addProjectToEmployee(id4,proj4);
break;
/* more cases */
}
} while (choice !=13);
检查案例4中的陈述3.
这是运行程序时发生的事情:
Enter your choice: 4
Please give the full information about the project
Project code: 66677
Project Title: Project Bonus in Percent:
答案 0 :(得分:1)
input.nextInt()
没有读取行尾,因此'为什么.nextLine()
被转义的效果,而实际上.nextLine()
正在读取行尾.nextInt()
在输入流中未读取。在.nextLine()
后,您需要额外.nextInt()
。
<强>更新强>
执行以下操作:
System.out.print("Project code: "); int code = input.nextInt();
input.nextLine(); // this is what you need to add
System.out.print("Project Title: "); String title = input.nextLine();