Java 循环输出错误

标签 java arrays

我正在编写一个基本的java程序,根据用户输入输出员工姓名、年龄和部门。它有效,但输出采用员工的名字并将其放置在其他信息之后的输出中,并且不显示部门。我怀疑这与我使用的空格分隔符有关,但我不确定为什么。任何帮助都会很棒。

代码:

package SimpleJavaAssignment;

import java.util.*;

public class Company
{
  ArrayList<Department> deptList = new ArrayList<Department>();

  public Department checkDepartment(String name)
  {
    for(Department dept: deptList)
    {
      if(dept.getName().equals(name))
      {
      return dept;
      }
    }
    Department d = new Department(name);
    deptList.add(d);
    return d;
  }

  public static void main(String[] args)
  {

    System.out.println ("Please enter the employee information. First Name, Last Name, Age and Department, and press enter.");
    System.out.println ("Once complete entering employee information, press enter a second time.");


    Scanner in = new Scanner(System.in);
    Company c = new Company();
    String input = in.nextLine();


    while(in.hasNextLine() && input.length() != 0)
    {

    String[] inputArray = input.split(" ");
      Department d = c.checkDepartment(inputArray[0]);
      d.newEmployee(Integer.parseInt(inputArray[2]), inputArray[1], d);
      input = in.nextLine();
    }
    for(Department dept:c.deptList)
    {
      ArrayList<Employee> empList = dept.getEmployees();
      for(Employee emp: empList)
      {
      emp.printInfo();
      }
    }
  }    
}

预期输出:

Employee Name: Bob Jones Employee Age: 38 Department: Marketing   Age Is A Prime: false
Employee Name: Alonzo Morris Employee Age: 54 Department: Accounting Age Is A Prime: false
Employee Name: Beth Moore Employee Age: 27 Department: Tech Age Is A Prime: false

实际输出:

Employee Name: Jones Employee Age: 38 Department: Bob Age Is A Prime: false
Employee Name: Morris Employee Age: 54 Department: Alonzo Age Is A Prime: false
Employee Name: Moore Employee Age: 27 Department: Beth Age Is A Prime: false

最佳答案

猜测您的输入,我想说这就是您想要的:

 String[] inputArray = input.split(" ");
 Department d = c.checkDepartment(inputArray[3]);
 d.newEmployee(Integer.parseInt(inputArray[2]), inputArray[0] + " " + inputArray[1], d);

请注意,split 在所有空格上进行拆分,包括每个员工的名字和姓氏。

关于Java 循环输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24337462/

相关文章:

java - 从 runnable 调用函数

arrays - 将每个数字 a[i] 替换为其右侧的下一个更高的数字,

c - 在 C : square brackets vs. 指针中传递数组

java - 在整个部署项目中查找资源

java - "public static final long USER_ACCOUNT = 32L"是什么意思?后缀L在长变量中意味着什么?

java - 如何返回图像

java - mongoDB:数组中不存在的文档的 $inc

javascript - 使用javascript的过滤器时如何获取排除的元素

arrays - 为什么我不能在其 willSet 事件中从数组中删除元素?

java - 将对象成员写入包裹