简体   繁体   English

Java 扫描仪合并线

[英]Java Scanner merging lines

I am trying to use a for loop to ask for 3 pieces of user input which are then used to create a new instance of a class.我正在尝试使用 for 循环来询问 3 条用户输入,然后用于创建 class 的新实例。 It works for the first loop, but then the second loop I get this prompt on the console and it expects an integer input.它适用于第一个循环,但是第二个循环我在控制台上得到这个提示,它需要一个 integer 输入。

Enter the employee's name: adam
Enter their hours worked: 1
Enter the employee's pay rate: 1
Enter the employee's name: Enter their hours worked: 

The code to input the data looks like this:输入数据的代码如下所示:

for (int i = 0; i < 5; i++) {
            System.out.print("Enter the employee's name: ");
            String employeeName = input.nextLine();
            System.out.print("Enter their hours worked: ");
            int hoursWorked = input.nextInt();
            System.out.print("Enter the employee's pay rate: ");
            double payRate = input.nextDouble();
            employee[i] = new Payroll(employeeName, hoursWorked, payRate);

I saw other questions on this site that suggest I use input.next() instead of input.nextLine() but that solution did not work either.我在这个网站上看到了其他问题,建议我使用 input.next() 而不是 input.nextLine() 但该解决方案也不起作用。 How do I get the input lines to separate like they should?如何让输入行像他们应该的那样分开?

The problem is here:问题在这里:

 double payRate = input.nextDouble();

With nextDouble , the scanner just stops when finishes reading the double value, skipping the rest of the line, including \n .使用nextDouble ,扫描仪在完成读取double精度值时停止,跳过该行的 rest ,包括\n

The second time the nextLine() is called, it just reads the end of the double input you entered before, and continues with " Enter their hours worked ", setting the employeeName empty after the first iteration.第二次调用nextLine()时,它只是读取您之前输入的双输入的结尾,并继续“输入他们的工作时间”,在第一次迭代后将employeeName设置为空。

As it is, your code could only work if you enter the value of the rate separated by the following employee name, like this (ugly):事实上,您的代码只有在您输入由以下员工姓名分隔的费率值时才能工作,如下所示(丑陋):

  Enter the employee's pay rate: 3559 James

Make the scanner force reading the end of the "double" line at the end of the loop:使扫描仪强制读取循环末尾“双”行的末尾:

for (int i = 0; i < 5; i++) 
{
    System.out.print("Enter the employee's name: ");
    String employeeName = input.nextLine();
    System.out.print("Enter their hours worked: ");
    int hoursWorked = input.nextInt();
    System.out.print("Enter the employee's pay rate: ");
    double payRate = input.nextDouble();
    employee[i] = new Payroll(employeeName, hoursWorked, payRate);
      
    //this
    if (i<4)
      input.nextLine();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM