java - 如何在java中读取循环内带有空格的字符串?

标签 java string loops whitespace

我们都知道,使用方法 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/

相关文章:

java: 从 xml 中删除 cdata 标签

java - 在不知道方法调用的参数的情况下使用mockito.when

java - 二分查找的比较次数

c# - 按字母顺序从字符串中查找并计算后一对

c# - 如何处理 C# 中引号内的引号?

c - 根据用户的输入结束循环

java - Servlet 不会重定向我

string - 将字符串转换为 Spring 资源的方法

php - 在 while 循环中提交表单后显示信息并将新记录上传到 MySQL 表中

java - for 循环中列表中的字符串比较