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 に答える