2012-07-25 81 views
0

我正在使用ArrayList對象來創建僱員類型的僱員對象...我實現類,它似乎工作,但我的問題是,當我插入員工到ArrayList它自動doesn'不要插入它。這是爲什麼?ArrayList對象

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

/** 
* 
* @author 
*/ 

import java.util.*; 

class Employee { 

    private String fname; 
    private String lname; 



    public Employee (String fname, String lname){ 
     this.fname = fname; 
     this.lname = lname; 
    } 

    public Employee(){ 
    } 

    public String getLastName(){ 
      return this.lname; 
    } 

    public void setLastName(String lname){ 
      this.lname = lname; 
    } 

    public String getFirstName(){ 
     return this.fname; 
    } 

    public void setFirstName (String fname){ 
     this.fname = fname; 
    } 

    public String toString(){ 
     return this.getClass().getName() +" [ " 
       + this.fname + " " 
       + this.lname + " ]\n "; 
    } 

    public Object clone(){ //Object is used as a template 
     Employee emp; 
     emp = new Employee(this.fname, this.lname); 

     return emp; 
    } 
} 

//start of main 
public class main 
{ 
    static Scanner input = new Scanner(System.in); 

    public static final int MAX_EMPLOYEES = 10; 

    public static void main(String[] args) { 


     String fname, lname; 
     int num; 

     System.out.print("Enter the number of employees in your system: "); 
     num = input.nextInt(); 

     ArrayList<Employee> emp = new ArrayList<Employee>(num); 

     System.out.print("Enter the first name: "); 
     fname = input.next(); 
     System.out.println(); 

     System.out.print("Enter the last name: "); 
     lname = input.next(); 
     System.out.println(); 

     for (int x = 1; x < num; x++) 
     { 
      System.out.print("Enter the first name: "); 
      fname = input.next(); 
      System.out.println(); 

      System.out.print("Enter the last name: "); 
      lname = input.next(); 
      System.out.println(); 

      emp.add(new Employee(fname,lname)); 
     } 

     num = emp.size(); 
     System.out.println(num); 
     System.out.println(emp); 


    } 
} 
+0

*它不會將第一個員工添加到ArrayList – fkianos15 2012-07-25 03:40:22

+0

僅供參考不要求'emp.size()'總是返回初始化列表的數量。它的目的是自動增加尺寸,如果更多的項目被添加它將擴大 – Russ 2012-07-25 03:50:13

回答

5

地址:

emp.add(new Employee(fname,lname)); 

for循環之前或重寫for循環條件爲:

for (int x = 0; x < num; x++) 

和擺脫

System.out.print("Enter the first name: "); 
fname = input.next(); 
System.out.println(); 

System.out.print("Enter the last name: "); 
lname = input.next(); 
System.out.println(); 

BEF的找到for循環。

+1

非常感謝...你完全幫助我與此。 int x確實需要初始化爲0 – fkianos15 2012-07-25 15:51:35

0

您的循環運行時間比所需時間少1秒。

 
for(int i=0;i<num; i++){ 

這應該解決它。

+0

除了它會爲員工多花一分鐘時間。如果你也擺脫了要求Employee的'for'循環的代碼,這將起作用 – Russ 2012-07-25 03:51:33