带循环的Java输出错误

时间:2014-06-21 01:31:06

标签: 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

2 个答案:

答案 0 :(得分:2)

猜猜你的意见,我说这就是你想要的:

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

请注意split分割所有空格,包括每位员工的名字和姓氏。

答案 1 :(得分:0)

你正在分裂空格:

String[] inputArray = input.split(" ");

&#39; Bob Jones&#39;包含一个空间。因此,您的拆分可能会导致元素位于不同的位置。

如果所有文件条目都遵循&#39;两个名称&#39;使用空格格式,请尝试以下更改:

 String department = inputArray[0];
 String fullName = inputArray[1] + " " + inputArray[2]
 int age = Integer.parseInt(inputArray[3]);

 Department d = c.checkDepartment(department);
 d.newEmployee(age, fullName, d);

用于拆分的实际数字显然取决于每条线的结构。此拆分假定该行采用以下格式:

营销Bob Jones 54

但是最好用引号包装每个条目,然后使用正则表达式来分割每个元素&#39; (There are a number of stackoverflow solutions relating to this method)。这样两种方式:

  • &#34;营销&#34; &#34; Bob Jones&#34; &#34; 54&#34;
  • &#34;营销&#34; &#34;鲍勃&#34; &#34; 54&#34;

可以使用相同的代码从同一个文件进行处理。