2014-06-21 142 views
0

我在寫一個基本的Java程序,根據用戶輸入輸出員工姓名,年齡和部門。它是有效的,除了輸出是在員工的名字和其他信息和部門沒有顯示之後放在輸出中。我懷疑它與我正在使用的空格分隔符有關,但我不知道爲什麼。任何幫助都是極好的。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 
+1

如果您向我們展示實際產生輸出的代碼,它會有多好? –

+0

給我們輸入請:) –

+1

請注意,你永遠不能可靠地拆分空間名稱 - 有效的名字和姓氏包含空格而不是連字符,例如「Anna Mae van der Westhuizen」。 –

回答

2

猜你的投入,我會說這是你想要的東西:

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

注意,split分割上的所有空格,包括每個員工的名字和姓氏。

0

要拆分的空間:

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

'鮑勃瓊斯'包含一個空間。所以你的分裂可能導致不同地方的元素超出你的期望。

如果所有文件條目將按照「兩名」用空格的格式,請嘗試以下變化:

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); 

用於拆分顯然將取決於各行的結構的實際數字。這種分裂假定行的格式如下:

營銷鮑勃·瓊斯54

但是,這將是更好的做法,包帶引號的每個條目,然後使用正則表達式來分割每個「元素」(There are a number of stackoverflow solutions relating to this method) 。這種方式既:

  • 「市場營銷」,「鮑勃·瓊斯」,「54」
  • 「市場營銷」,「鮑勃」,「54」

可能來自同一個文件進行處理,用相同的代碼。