2012-08-24 101 views
1

好的,我有點難以理解。我會直截了當地說我正在做一項家庭作業,而且我已經陷入了一個絆腳石。我確信我錯過了一些顯而易見的事情,但經過幾個小時的搜索互聯網和教科書來嘗試找到答案,我就會碰壁,我希望有人能指點我正確的方向。Java:無法打印ArrayList中的元素

我創建了一個名爲「員工」的類,它定義了一個員工對象,它有員工姓名和銷售總額的getter和setter方法。它看起來如下:

public class employee { 
    private String employeeName; 
    private double yearSales; 

    public employee(String employeeName, double yearSales) 
    { 
     this.employeeName = employeeName; 
     this.yearSales = yearSales; 
    } 

    public void setName(String employeeName) 
    { 
     this.employeeName=employeeName; 
    } 

    public void setSales(double yearSales) 
    { 
     this.yearSales=yearSales; 
    } 

    public String getEmployee() 
    { 
     return employeeName; 
    } 

    public double getYearsSales() 
    { 
     return yearSales; 
    } 
} 

然後,我有一個方法,旨在實例化一個包含員工對象的ArrayList。我能夠儘可能獲得儘可能創建ArrayList和添加信息,如下所示:

public ArrayList employeeArray(String name, double sales) 
{ 

    //Instantiate a new ArrayList object 
    ArrayList employeeList = new ArrayList(); 

    //Initialize the values in the ArrayList 
    employeeList.add(new employee(name, sales)); 

    return employeeList; 

} 

當我遇到的麻煩是試圖打印出從ArrayList name的值,如下圖所示:

System.out.println(employeeList.get(0).getEmployee()); 

我只加一個元素故該指標值應該是正確的,我不是很久以前,在另一個Java課程的ArrayList工作,並能對那些任務做類似這樣的東西在我的代碼。如果我需要澄清更多關於此的事情,我會很樂意。當然,對此的任何幫助都非常感謝。

+0

什麼是錯誤? – MadProgrammer

+0

就樣式而言,Java類名通常以大寫字母開頭('class Employee ...'而不是'class employee ...')。 –

+0

今天早上我夢見了這個夜晚後才醒來,意識到我沒有包括這個錯誤。 「找不到符號,符號:method getEmployee();」 – morris295

回答

4

如果您的Java SE> = 5,則應該使用Generics,因此而不是ArrayList,請使用ArrayList<employee>。否則,你需要轉換其類型從ObjectEmployee

System.out.println(((employee)employeeList.get(0)).getEmployee()); 

此外,在Java 類和接口名稱應該啓動以大寫字母。

+0

感謝您的迴應,我現在能夠成功編譯我的代碼,這要歸功於您的建議。 – morris295

3
public ArrayList<employee> employeeArray(String name, double sales) 
{ 

    //Instantiate a new ArrayList object 
    ArrayList<employee> employeeList = new ArrayList<employee>(); 

    //Initialize the values in the ArrayList 
    employeeList.add(new employee(name, sales)); 

    return employeeList; 

} 
0

youre設法實例化一個新ArrayList每次調用employeeArray()方法。嘗試維護一個共同的ArrayList並使用此方法爲其添加元素。

而且+1使用generics
如果你是新來的Java,那麼請閱讀此鏈接,以及:"Java Programming Style Guide (Naming Conventions)"

假設你一個名爲EmployeeList類,你必須定義這個方法employeeArray(),你可以更新它在列表中維持新名稱如下(注意,這是一個樣品溶液,你顯然是歡迎它以適應您的需求):

public class EmployeeList{ 
    private ArrayList<Employee> employeeList; 

    public EmployeeList(){ 
     //Initializing the employee arraylist 
     employeeList = new ArrayList<Employee>(); 
    } 

    public ArrayList<Employee> employeeArray(String name, double sales){ 
     //Initialize the values in the ArrayList 
     employeeList.add(new Employee(name, sales)); 

     return employeeList; 
    } 
} 

而且請注意在上面的代碼中使用泛型和命名約定。這可能對你有所幫助。

+0

非常感謝,所有來自此主題的建議都非常有幫助。同時感謝您提供風格指南的鏈接和泛型的建議。 – morris295