2013-04-30 29 views
0

這是我第一次使用數組列表創建一個程序,我遇到了一個小問題。對代碼的簡短描述......列出員工的信息(ID號,姓名,開始日期,工資等),並將其輸出到「employeeTArea」中。如何列出數組?

public class EmployeeView extends FrameView { 
/** Define the ArrayList */ 
ArrayList <String> inventory = new ArrayList <String>(); 

public EmployeeView(SingleFrameApplication app) { 

}// </editor-fold> 

private void AddActionPerformed(java.awt.event.ActionEvent evt) { 

    String c; 
    String ID, firstName, lastName, annualSal, startDate; 

    ID = IDField.getText(); 
    firstName = firstNameField.getText(); 
    lastName = lastNameField.getText(); 
    annualSal = annualSalField.getText(); 
    startDate = startDateField.getText(); 

    c = new String (ID); 
    c = new String (firstName); 
    c = new String (lastName); 
    c = new String (annualSal); 
    c = new String (startDate); 
    inventory.add(c); 
} 

private void ListActionPerformed(java.awt.event.ActionEvent evt) { 

的問題是在這裏略低於......雖然你可能無法看到它之後的get(x)的(名字,姓氏,ID等等等等)突出紅色的一切。就是這些話。當然,這會產生一個問題,因爲我通過按下「addButton」將員工信息存儲在數組中,當我按下「listButton」來顯示時,我無法再訪問這些信息。

String temp=""; 

    for (int x=0; x<=inventory.size()-1; x++) { 
     temp = temp + inventory.get(x).ID + " " 
       + inventory.get(x).firstName + " " 
       + inventory.get(x).lastName + " " 
       + inventory.get(x).annualSal + " " 
       + inventory.get(x).startDate + "\n"; 
    } 
    inventoryOut.setText(temp); 

    class Company { 
    String ID, firstName, lastName, annualSal, startDate, mileage; 

    Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) { 
     ID = _ID; 
     firstName = _firstName; 
     lastName = _lastName; 
     annualSal = _annualSal; 
     startDate = _startDate; 
    } 
} 

}

+0

你確定設置'C'了很多不同的東西。 – 2013-04-30 22:27:51

+0

你的'inventory'是'String'的'ArrayList',因此它只保存'String's,並且該類沒有'firstName','lastName'等。我想你列出了錯誤的類型。你可能需要一個你自己類的'List',一個包含這些屬性的類。 – 2013-04-30 22:30:09

+0

我看到你正在宣佈一個「班級公司」,但沒有看到你在任何地方使用它? – SOfanatic 2013-04-30 23:07:05

回答

0

你的問題

看看那裏聲明這些變量。他們被宣佈爲local,當他們需要是global。在任何方法聲明之外聲明它們。

也期待在此聲明:

ArrayList <String> inventory = new ArrayList <String>(); 

你必須參數inventory鍵入String,但是你想使用它喜歡它是Employee類型。

約定

的Java約定規定,你不應該直接訪問成員;你應該使用accessorsmutators。例如:

public String getID() 
{ 
    return ID; 
} 

一些代碼的

c = new String (ID); 
c = new String (firstName); 
c = new String (lastName); 
c = new String (annualSal); 
c = new String (startDate); 
inventory.add(c); 

你在做什麼這裏宣佈c作爲一個新的String,在ID值。然後宣佈它作爲一個新的String的值爲firstName等。基本上,你只是每次加入startDate。更不用說所有這些值已經是String對象的事實了。從它們創建新的String對象實際上沒有任何好處。

0

ArrayList <String> inventory = new ArrayList <String>();這是字符串 的ArrayList所以inventory.get(x)是一個String

你應該把爲ArrayList <Employee> inventory = new ArrayList <Employee>();

+0

我原本是以這種方式開始的,然而「僱員」是加下劃線的紅色。 – Que 2013-04-30 22:33:04

+0

你有一個叫做Employee的類嗎?如果是的話,你應該導入它 – 2013-04-30 22:42:23

+0

啊,正如我在你的代碼中看到的,類名實際上是「公司」而不是「員工」 – 2013-05-01 00:39:16