我有代码从数组中删除一个条目,然后将所有元素向下移动一个索引,这样空的空格就会留在数组的末尾。问题是数组中的最后一个条目被复制到已删除的索引中。
这是输入所有记录时的数组:
[entryOne, entryTwo, entryThree, entryFour, entryFive, entrySix, entrySeven, entryEight, entryNine, entryTen]
然后我运行我的代码来删除索引5并打印数组,这就是显示的内容:
[entryOne, entryTwo, entryThree, entryFour, entryFive, entrySeven, entryEight, entryNine, entryTen, entryTen]
如何才能将最终索引清空?
添加记录代码:
static void addStudent() {
if (nameArrayCount < 10) {
System.out.println("Enter the student's name in the following format - surname, forename: ");
studentName = input.next();
studentNamesArray[nameArrayCount] = studentName;
nameArrayCount = nameArrayCount + 1;
}
else if (nameArrayCount == 10) {
System.out.println("******Array is full, please delete a student before adding another.*****");
}
if (markArrayCount < 10){
System.out.println("Enter the first mark: ");
markOne = input.nextInt();
System.out.println("Enter the second mark: ");
markTwo = input.nextInt();
System.out.println("Enter the third mark: ");
markThree = input.nextInt();
studentMarksArray[markArrayCount][0] = markOne;
studentMarksArray[markArrayCount][1] = markTwo;
studentMarksArray[markArrayCount][2] = markThree;
markArrayCount = markArrayCount + 1;
}
}
删除记录代码:
static void deleteStudent() {
System.out.println("Which student would you like to delete?");
for(int i=0;i<10;i++) {
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
for(int i = studentChoice+1; i<studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
nameArrayCount = nameArrayCount -1;
}
答案 0 :(得分:5)
您必须手动将其设置为null
。
for(int i = studentChoice+1; i<studentNamesArray.length; i++) {
studentNamesArray[i-1] = studentNamesArray[i];
}
studentNamesArray[studentNamesArray.length - 1] = null;
如果你要这样做,你可能想要使用ArrayList
。删除/添加值要好得多。还有一个toArray()
方法可以让你在真正需要时以数组形式返回它(我不希望这个代码示例使用那么多学生条目,这将是一个昂贵的操作)。