arraylist不打印第一个元素

时间:2017-04-04 17:37:41

标签: java

我正在尝试编写一些java代码,但我得到了一个例外。 我的问题是,当我尝试添加运动员时,我得到一个空指针异常 该计划是接受运动员和计算得分的平均值 这是我的代码

public class AthleteTest {

        final int  MAX_ATHELETE = 200;
        private int count=0;    
        Athlete[] at = new Athlete[MAX_ATHELETE];
        Scanner sc = new Scanner(System.in);

    public void addAthletes(){
            char add = 'Y';
            while(add == 'Y'){

                System.out.println("name:");
                String name = sc.nextLine();
                at[count].setName(name);

                //Get athlete's Id number
                System.out.println("id :");
                int id = sc.nextInt();
                at.setId(id);

                //sc.nextLine();

                count++;


                System.out.println("Would you like to add another athlete?   Y / N");
                add = Character.toUpperCase(sc.next().charAt(0));
                sc.nextLine();
            }
        }
    }


    my Athlete class is as follow

    public class Athlete {

        private String name;
        private int id;

        private double [] grades;

        public Athlete(){
            this.name = null;
            this.id= 0;
        }

        public Student(String name, int id){
            this.name = name;
            this.id= id;
        }

        public String getName() {
            return name;
        }

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

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }
    }

1 个答案:

答案 0 :(得分:0)

您获得异常是因为您在实例化之前尝试访问运动员对象。通过这个初始化:

 Athlete[] at = new Athlete[MAX_ATHELETE];

你只是创建了一个举办运动员实例的地方。

以这种方式更改您的循环代码:

System.out.println("name:");
String name = sc.nextLine();
at[count] = new Athlete(); // Add this line
at[count].setName(name);

你应该没事。