【发布时间】:2019-12-17 00:31:09
【问题描述】:
在ArrayList 的指定索引处添加元素时出现错误我正在使用循环和变量,每次循环时它都会增加
-
我尝试使用命令
arrayListName.add(index,thing)但这在第二次分配时给我一个错误 问题 ==> https://ibb.co/ZSQvywY . - 我尝试在没有索引的情况下循环,但这一直在索引 [0] 中分配
public class CollegeSystem {
public static void printOptions() {
System.out.println("Welcome to our university!");
System.out.println("Operations:");
System.out.println("1- College");System.out.println("a) Number of Departments");System.out.println("b) Number of Courses");System.out.println("c) Number of Professors");System.out.println("d) Number of Students");System.out.println("e) Report");
System.out.println("2- Department");System.out.println("a) New");System.out.println("b) Number of Courses");System.out.println("c) Number of Students");System.out.println("d) Is Full");System.out.println("e) Enroll");System.out.println("f) Report");
System.out.println("3- Course");System.out.println("a) New");System.out.println("b) Number of Students");System.out.println("c) Assign");System.out.println("d) Is assigned");System.out.println("e) Professor Name");System.out.println("f) Is Full");System.out.println("g) Enroll");System.out.println("h) Report");
System.out.println("4- Professor");System.out.println("a) New");System.out.println("b) Display Salary");System.out.println("c) Get Raise");System.out.println("d) Report");
System.out.println("5- Student");System.out.println("a) New");System.out.println("b) Report");
System.out.println("6- Quit");
}
public static void main(String[] args) {
// TODO code application logic here
printOptions() ;
Scanner in = new Scanner(System.in) ;
int d = 0 , c = 0 , p = 0 , s=0 ;
College AinShams = new College() ;
while (true){
String option = in.nextLine() ;
if(!"6".equals(option)) {
if ("2a".equals(option)) { // Define new department
System.out.println("Department Name:");
String depName = in.nextLine() ;
System.out.println("Department Description:");
String depDescripe = in.nextLine() ;
System.out.println("Department Max Students:");
int max_num = in.nextInt() ;
in.nextLine() ;
Department Department_Name =
new Department(depName, depDescripe, max_num);
List<Department> departmentList;
//here create a new arrayList
departmentList = new ArrayList<>();
//try to add element without index
// departmentList.add(Department_Name);
//try to add element with index
departmentList.add(d, Department_Name);
d++ ;
AinShams.setDepart(departmentList);
}
}
}
}
}
我需要在每次循环时添加一个元素而不删除旧数据。
【问题讨论】:
-
你的代码有几个问题:(1)你总是重新创建
departmentList,因此得到一个空列表,(2)如果你想在最后添加元素,为什么不直接调用@ 987654326@?, (3) 阅读 Java 代码约定 - 这应该会让您意识到不鼓励使用像Department_Name这样的名称。它应该是departmentName,因为类型是Department而不是String(或任何用来表示名称的),所以department可能会更好。