欢迎使用CSDN-markdown编辑器

来源:互联网 发布:众安 社交网络事业部 编辑:程序博客网 时间:2024/05/19 00:17

慕课网Java第三季学习

6-2 学生选课—判断set中课程是否存在
Exception in thread “main” java.lang.NullPointerException
按照老师的代码会报错,解决方案是修改Scanner的限定符。
private Scanner console;
变成
public Scanner console;

package com.imooc.collection;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Scanner;public class SetTest4 {    public List<Course> coursesToSelect;    public SetTest4(){        coursesToSelect = new ArrayList<Course>();          }    public Scanner console;    public Student student;    public void testAdd(){        Course[] course ={new Course("1","数据结构"),new Course("2","C语言"),                new Course("3","离散数学"),new Course("4","汇编语言"),                new Course("5","高等数学"),new Course("6","大学英语")};        coursesToSelect.addAll(Arrays.asList(course));    }    //创建学生对象并选课(先固定一次选3门课),选完课输出一下学生对象的属性(调用TestPrint方法)    public void creatStudentAndSelectCours(){        student = new Student("1","小明");        console = new Scanner(System.in);        int i = 0;        while(i<3){            System.out.println("请输入要选的课程的序号:");            String id = console.next();            //先判断要选的序号在原来待选的课程里是否有,有,才能放进去,遍历比较            for(Course cr: coursesToSelect){                if(cr.id.equals(id)){                    student.courses.add(cr);                            i++;                }else continue;            }                   }        TestPrint(student);    }    //打印学生对象里面的属性,包括ID,name,已选课程    public void TestPrint(Student student){        for(Course cr:student.courses){            System.out.println("选择了课程:"+cr.id+":"+cr.name);        }    }    //用名字判断学生的已选课程中是否有一门课 学生的已选课程属性是HashSet    public void testSetContain(){        System.out.println("输入课程名称");        //Scanner s = new Scanner(System.in);        String name  = console.next();        //这里console因为定义引用过了所以直接用        Course cr = new Course();        cr.name = name;        //boolean a = student.courses.contains(cr);        System.out.println(student.courses.contains(cr));    }    public static void main(String[] args) {        SetTest4 st2 = new SetTest4();        st2.testAdd();        st2.creatStudentAndSelectCours();        st2.testSetContain();    }}
原创粉丝点击