我的工作是创建一个程序,用户输入一个数字,它会搜索输入的数字 在我的数组存储中;如果存在,则会显示“Found”并显示数组中的所有元素并删除 Found 值;
它是这样的:
我已经完成了我的代码,但有一个问题; 如果找到它,它不会显示数组的所有元素,也不会删除它。 发生错误
顺便说一句,这是我的代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] ArrayApp = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20 };
System.out.println("ArrayList:");
for (int x = 0; x < ArrayApp.length; x++) {
System.out.print(ArrayApp[x] + " ");
}
System.out.println();
System.out.print("Enter a number: ");
int num = input.nextInt();
int x;
for (x = 0; x < ArrayApp.length; x++) {
if (ArrayApp[x] == num) {
break;
}
}
if (x == ArrayApp.length) {
System.out.println("Cant find: " + num);
} else {
System.out.println("Found");
}
for (int k = x; k < ArrayApp.length; k++) {
ArrayApp[k] = ArrayApp[k + 1];
}
for (x = 0; x < ArrayApp.length; x++) {
System.out.print(ArrayApp[x] + " ");
}
}
那么你能帮我找出我的代码有什么问题吗?
最佳答案
ArrayApp[k] = ArrayApp[k + 1];
当 k = ArrayApp.lenngth-1 时,会抛出 ArrayIndexOutOfBounds 异常,因为 k+1 超出范围。
您应该更改范围:
for (int k = x; k < ArrayApp.length - 1; k++) {
ArrayApp[k] = ArrayApp[k + 1];
}
在打印输出数组时,如果删除了一个元素,则不想打印最后一个元素,因为它会被打印两次(因为数组的长度不会改变)。
int length = ArrayApp.length;
if (x < ArrayApp.length) // adjust the number of elements to be printed after
// one element was removed
length--;
for (x = 0; x < length; x++) {
System.out.print(ArrayApp[x] + " ");
}
关于java - 如果已经找到数组,则无法删除该数组(数组搜索排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27418378/