package collection_map_List; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class SetTest { public static List<Course> courses; public SetTest() { this.courses=new ArrayList<Course>(); } public void addcourse() { Course course1=new Course("0102", "数学"); Course course2=new Course("0103", "数据结构"); courses.add(course1); courses.add(course2); Course c1=new Course("2", "英语"); courses.add(2,c1); } public void add2(){ Course[] course={ new Course("001", "english"),new Course("002", "math")}; //2.1、addAll()添加方式 courses.addAll(Arrays.asList(course)); Course[] c1={ new Course("05", "心理学"),new Course("06", "历史")}; courses.addAll(Arrays.asList(c1)); } public void allCourse(){ //遍历集合 for(Course c: courses){ System.out.println(c.id+"\t"+c.name); } } public static void stuCourse(Student student1){ for(Course course : student1.course){ System.out.println(course.id+","+course.name); } } public static void main(String[] args){ Scanner scanner=new Scanner(System.in); SetTest lt=new SetTest(); lt.addcourse(); lt.add2(); System.out.println("....所有课程清单....................."); lt.allCourse(); System.out.println("................................."); Student student1=new Student("311309030","哒哒"); System.out.println("···········输入要添加课程的编号············"); for(int i=0;i<3;i++){ String sc=scanner.next(); for(Course cou:courses){ if(cou.id.equals(sc)){ //System.out.println(cou.name); student1.course.add(cou); if(i<2){ System.out.println("成功添加一门课程,请继续添加课程:"); } else{ System.out.println("添加课程完毕!"); } } } } System.out.println("学生:"+student1.id+"\t"+student1.name+" 的课程有:"); stuCourse(student1); } } 001 english 002 math 05 心理学 06 历史 ................................. ···········输入要添加课程的编号············ 001 Exception in thread "main" java.lang.NullPointerException at collection_map_List.SetTest.main(SetTest.java:55) 为什么 一添加课程 报空指针错误,55行
/** * 课程类 * @author Administrator * */ public class Course { public String id; public String name; public Course(String id, String name) { this.id = id ; this.name = name; } public Course() { } } import java.util.HashSet; import java.util.Set; /** * 学生类 * @author Administrator * */ public class Student { public String id; public String name; public Set<Course> courses; public Student(String id, String name) { this.id = id; this.name = name; this.courses = new HashSet<Course>(); } }
35.for(Course course : student1.courses){
55.student1.courses.add(cou);
....所有课程清单.....................
0102 数学
0103 数据结构
2 英语
001 english
002 math
05 心理学
06 历史
.................................
···········输入要添加课程的编号············
001
成功添加一门课程,请继续添加课程:
05
成功添加一门课程,请继续添加课程:
0102
添加课程完毕!
学生:311309030 哒哒 的课程有:
001,english
0102,数学
05,心理学
运行没有问题呀,可能是你学生类,或者课程类的错误吧!