package frameWork; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class SetTest { public List<ArrayListStudent> coursesToSelect; public SetTest() { coursesToSelect = new ArrayList<ArrayListStudent>(); } public void testAdd() { //创建一个课程对象,并通过调用add方法,添加到备选课程List中 ArrayListStudent cr1 = new ArrayListStudent("1", "数据结构"); coursesToSelect.add(cr1); //这里添加(ArrayListStudent)的原因是对象存入集合后类型变为object,这里强制转换对象的类型 ArrayListStudent temp = (ArrayListStudent) coursesToSelect.get(0); //System.out.println("添加课程:" + temp.id + ":" + temp.name); ArrayListStudent cr2 = new ArrayListStudent("2", "Java"); coursesToSelect.add(1, cr2); ArrayListStudent temp2 = (ArrayListStudent) coursesToSelect.get(1); //System.out.println("添加课程:" + temp2.id + ":" + temp2.name); //抛出数组下标越界抛出异常 //ArrayListStudent cr3 = new ArrayListStudent("3","C++"); //coursesToSelect.add(4,cr3); ArrayListStudent[] arrayListStudents = { new ArrayListStudent("3", "离散数学"), new ArrayListStudent("4", "汇编语言") }; coursesToSelect.addAll(Arrays.asList(arrayListStudents)); ArrayListStudent temp3 = (ArrayListStudent) coursesToSelect.get(2); ArrayListStudent temp4 = (ArrayListStudent) coursesToSelect.get(3); //System.out.println("添加课程:" + temp3.id + ":" + temp3.name //+ ";" + temp4.id + ":" + temp4.name); ArrayListStudent[] arrayListStudents2 = { new ArrayListStudent("5", "微分几何"), new ArrayListStudent("6", "数值分析") }; coursesToSelect.addAll(2, Arrays.asList(arrayListStudents2)); ArrayListStudent temp5 = (ArrayListStudent) coursesToSelect.get(2); ArrayListStudent temp6 = (ArrayListStudent) coursesToSelect.get(3); // System.out.println("添加课程:" + temp5.id + ":" + temp5.name // + ";" + temp6.id + ":" + temp6.name); } public void testForEach() { System.out.println("有如下课程待选(通过for each访问):"); for (Object obj : coursesToSelect) { ArrayListStudent cr = (ArrayListStudent) obj; System.out.println("课程:" + cr.id + ":" + cr.name); } } public static void main(String[] args) { SetTest st = new SetTest(); st.testAdd(); st.testForEach(); //创建一个新的学生对象 Student student = new Student("1", "章北海"); System.out.println("你好!" + student.name + "请选课"); //创建一个Scanner对象,接收键盘输入的ID Scanner console = new Scanner(System.in); //创建一个循环,循环三次,将输入的课程id加入到学生选课中 for (int i = 0 ; i < 3 ; i++) { System.out.print("请输入课程id:"); String courseID = console.next(); for (ArrayListStudent cr : st.coursesToSelect) { if (cr.id.equals(courseID)) { student.arrayListStudents.add(cr); } } } st.testForEachForSet(student); } public void testForEachForSet(Student student) { //循环完毕后打印输出学生所选的课程 for (ArrayListStudent cr : student.arrayListStudents) { System.out.println("选择的课程为:" + cr.id + ":" + cr.name); } } }
输出为:
有如下课程待选(通过for each访问): 课程:1:数据结构 课程:2:Java 课程:5:微分几何 课程:6:数值分析 课程:3:离散数学 课程:4:汇编语言 你好!章北海请选课 请输入课程id:1 请输入课程id:2 请输入课程id:3 选择的课程为:3:离散数学 选择的课程为:2:Java 选择的课程为:1:数据结构
如图,请问为什么我输入的课程id是1,2,3 但是输出是确实3,2,1反着的。。
你可以尝试着多添加几门课程,你会发现排列是无序的,并没有什么正着来还是反着来