0

我正在使用 ArrayList 对象创建一个员工类型的员工对象...我实现了这个类,它似乎可以工作,但我的问题是,当我将员工插入 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);


    }
 }
4

2 回答 2

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

for循环之前。

于 2012-07-25T03:44:39.017 回答
0

您的循环运行时间比所需时间少 1。

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

这应该解决它。

于 2012-07-25T03:48:05.770 回答