0

我们都知道在运行程序时使用方法 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: 
4

1 回答 1

1

input.nextInt()不读取行尾,所以这就是为什么.nextLine()要转义的效果,而实际上.nextLine()是读取输入流中未读取的行尾.nextInt()。你需要一个额外的.nextLine()after .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();
于 2012-11-03T16:40:45.427 回答