java - 如果已经找到数组,则无法删除该数组(数组搜索排序)

标签 java arrays sorting search

我的工作是创建一个程序,用户输入一个数字,它会搜索输入的数字 在我的数组存储中;如果存在,则会显示“Found”并显示数组中的所有元素并删除 Found 值;

它是这样的: enter image description here

我已经完成了我的代码,但有一个问题; 如果找到它,它不会显示数组的所有元素,也不会删除它。 发生错误

enter image description here

顺便说一句,这是我的代码:

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/

相关文章:

java - 无法安装 m2e 生命周期映射

java - 从我的 jsp 引用外部项目时出现问题 - "ExternalClass cannot be resolved to a type"

c - C 中动态数组的删除操作

java - JTable 和排序

java - 从 double 转换为 int 并不总是只删除小数部分

java - 使用 JSch 执行命令

python - 如何使用 Twisted (python) 正确解析请求字符串

c# - 如何动态生成和填充多维数组

algorithm - 这些输入的合并排序的运行时间是多少

c# - 按值对 <key, value> 对进行高效排序