qq_慕丝4346553
2021-08-25 20:07
package com.imocc.example3; import java.util.*; public class ListText { public List courseToSelect; public ListText(){ this.courseToSelect = new ArrayList(); } public void courseAdd(String num,String cour){ Course a = new Course(); a.setId(num); a.setName(cour); courseToSelect.add(a); Course temp1 = (Course) courseToSelect.get(courseToSelect.size()-1); System.out.println("添加课程:"+temp1.getId()+":"+temp1.getName()); /** * Course b= new Course(); b.setId("3"); b.setName("生物"); Course[] temp2 = {b}; courseToSelect .addAll(Arrays.asList(temp2)); Course temp3 = (Course) courseToSelect.get(1); System.out.println("添加课程:"+temp3.getId()+":"+temp3.getName()); */ } public void textIterator(){ Iterator temp3 = courseToSelect.iterator(); while (temp3.hasNext()){ Course temp4 = (Course) temp3.next(); System.out.println("又如下课程待选:"+temp4.getId()+":"+temp4.getName()); } } public static void main(String[] args) { while(true) { System.out.println("------------添加课程输入数字1---------------"); System.out.println("------------查看课程输入数字2---------------"); System.out.println("------------退出程序输入数字3---------------"); Scanner input = new Scanner(System.in); int str = input.nextInt(); if (str==1) { ListText listText = new ListText(); System.out.println("输入添加的课程id和名称:"); //Scanner input = new Scanner(System.in); String num = input.next(); String cour = input.next(); listText.courseAdd(num, cour); }else if (str==2){ ListText listText = new ListText(); listText.textIterator(); }else if (str==3){ break; } } } }
把if (str==1) { ListText listText = new ListText(); 这里的ListText listText = new ListText();语句提到while上方, 否则每次都会重新new一个新对象把原来储存了数据的对象覆盖了
Java入门第三季
409792 学习 · 4340 问题
相似问题