Java:从用户输入的整数数组中删除重复项

时间:2017-11-10 22:04:10

标签: java arrays input

我试图使用java从用户输入的数组中删除重复项,并且我得到一个重复变量的错误,这是我到目前为止:

public class sortedArray {

  static int alter(int array[], int n) {
    if (n == 0 || n == 1)
      return n;
    int[] arr = new int[n];
    int r = 0;
    for (int i = 0; i < n - 1; i++)
      if (array[i] != array[i + 1])
        arr[r++] = array[i];
    arr[r++] = array[n - 1];
    for (int i = 0; i < r; i++)
      array[i] = arr[i];
    return r;
  }

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int[] array = new int[49];
    int n = array.length;

    System.out.print("enter some integers (enter -9999 to stop): ");
    for (int i = 0; i < array.length; i++) {
      array[i] = input.nextInt();
      if (array[i] == -9999) {
        break;
      }
      n = alter(array, n);
      for (int i = 0; i < n; i++) //getting error here on the i
        System.out.print(array[i] + " ");
    }
  }
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您的问题是您尝试在第一个i循环内重新声明for。您需要在第二个循环中使用另一个计数器变量:

for (int i = 0; i < array.length; i++) {
  array[i] = input.nextInt();
  if (array[i] == -9999) {
    break;
  }
  n = alter(array, n);
  for (int j = 0; j < n; j++) //getting error here on the i
    System.out.print(array[j] + " ");
}