打印出arraylist元素时出错

时间:2018-01-21 19:41:11

标签: java arraylist

这是一个小程序,可以添加和打印工人。调用打印方法时,我会收到一个输出,其元素与我添加的元素数相同。我无法理解我的错误在哪里。

public class Radnik {
    static List<Radnik> workers = new ArrayList<>();
    private String name;


    public static void main (String []args) {
        Radnik.add();
        for(Radnik r : workers) {
            System.out.println(r);
        }
    }
    public static void add () {
        String name;
        String answer;
        do {
            Scanner s = new Scanner(System.in);
            System.out.println("name");
            name = s.next();
            Radnik f = new Radnik();
            workers.add(f);
            System.out.println("More");
            answer = s.next();
        } while (answer.equals("yes"));
    }
} 

2 个答案:

答案 0 :(得分:3)

您从未将name设置为Radnik 我会添加构造函数Radnik(String name)来初始化name并添加一个getter和setter。

System.out.println(r)只会打印废话,因为它会调用Object.toString()。您必须覆盖toString()或调用其他方法来输出有意义的内容。

public class Radnik {
    static List<Radnik> workers = new ArrayList<>();
    private String name;


    public Radnik(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Radnik=[name=\""+name+"\"]";
    }

    public static void main (String []args) {
        Radnik.add();
        for(Radnik r : workers) {
            System.out.println(r);
        }
    }
    public static void add () {
        String name;
        String answer;
        do{
            Scanner s = new Scanner(System.in);
            System.out.println("name");
            name = s.next();
            Radnik f = new Radnik(name);
            workers.add(f);
            System.out.println("More");
            answer = s.next();
        } while (answer.equals("yes"));
    }
} 

答案 1 :(得分:0)

public class MainClass{
    private static List<Radnik> workers = new ArrayList<>();

    public static void main (String []args) {
        new MainClass().add();
        for(Radnik r : workers) {
            System.out.println(r.getName());
        }
    }

    public void add () {
        String name;
        String answer;
        do{
            Scanner s = new Scanner(System.in);
            System.out.println("name");
            name = s.next();
            Radnik f = new Radnik();
            f.setName(name);
            workers.add(f);
            System.out.println("More");
            answer = s.next();
        } while (answer.equals("yes"));
    }

    public class Radnik {

        private String name;

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

        public String getName() {
            return name;
        }
    }
}