我们都知道,使用方法 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:
最佳答案
input.nextInt()
不会读取行尾,因此这就是为什么 .nextLine()
的效果被转义,而实际上.nextLine()
正在读取 .nextInt()
在输入流中未读的行尾。在 .nextInt()
之后需要额外的 .nextLine()
。
更新:
执行以下操作:
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();
关于java - 如何在java中读取循环内带有空格的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13211167/