当我尝试删除数组中的元素时,为什么会得到-1

时间:2018-03-26 23:56:59

标签: java arrays indexing

我查看了已经发布的问题,但我仍然无法找到解决方案。

我的代码输出是:

  

输入整数:5
  输入5个整数:1
       2
       3
       4
  5
  输入要删除的号码:2
  -1

package array;

import java.util.*;
//import java.util.ArrayLists; 

public class DeleteFromArray {

    public static void main(String[] args) {

        int n = 0; // number of integers
        int d = 0; // the number to be deleted
        int count = 0;
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the number of integers: ");
        n = scan.nextInt();
        if (n <= 0) {
            System.out.println("Invalid input");
            System.exit(-1);
        }
        int[] buffer = new int[n];
        System.out.print("Enter " + n + " integers: ");

        for (int k = 0; k < buffer.length; k++) {
            buffer[k] = scan.nextInt();
        }

        System.out.print("Enter the number to be deleted: ");
        d = scan.nextInt();
        for (int i = 0; i < buffer.length; i++) {
            if (buffer[i] == d) {
                for (int j = 0; j < (buffer.length) - 1; j++) {
                    buffer[j] = buffer[j + 1];
                }
                count++;
                break;
            }

        }
        if(count ==0) {
            System.out.println("Element not found!");
        }
        else {
             System.out.print("Element Deleted Successfully..!!");
               System.out.print("\nNow the New Array is :\n");
               for (int i = 0; i < (buffer.length)-1; i++) {
                System.out.println(buffer[i]+ " ");
            }
        }
        scan.close();
    }

}

1 个答案:

答案 0 :(得分:2)

你的for循环

for (int j = 0; j < (buffer.length) - 1; j++) {
                buffer[j] = buffer[j + 1];
            }

将无法正常工作,因为它会将0索引处的值替换为索引1处的值,依此类推。您想要做的只是初始化j=i,其中i是d的索引。它会用下一个替换这个值。

for (int j = i; j < (buffer.length) - 1; j++) { 
                    buffer[j] = buffer[j + 1];
                }

尝试这个循环它会起作用。