2012-07-25 77 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