如何将唯一值插入Java中的二维数组



对于此程序,要求用户为数组中的每个单元格提供一个值,并且必须不允许输入结构中其他位置的值。注意我只能使用数组,而不使用其他数据结构。

如何修改代码执行此操作?

这是我的代码:

public class UniqueArrayAdd {
  int i, j;
  public UniqueArrayAdd() {
    int[][] arr3 = new int[3][3];
    Scanner scan = new Scanner(System.in);
    for (i = 0; i < arr3.length; i++) {
        for (j = 0; j < arr3.length; j++) {
            System.out.println("Enter a value");
            // What to do to check the duplication
            // If the input value is not duplicated then insert other wise               //give "Already exist" message
            arr3[i][j] = scan.nextInt();
        }
    }
    // For printing array
    for (i = 0; i < arr3.length; i++) {
        for (j = 0; j < arr3.length; j++) {
            System.out.print(arr3[i][j] + "t");
        }
        System.out.println("");
    }
  }
  public static void main(String[] args) {
    new UniqueArrayAdd();
  }
}

天真的方法是在数组的所有元素上迭代并进行比较。为此,您可以"重复使用"正在打印数组元素的代码。

我会尝试将代码转移到一个单独的方法中。它可以例如如果包含该值,则返回true,否则为false。像这样的东西

boolean exists(final int value) {
 for (i = 0; i < arr3.length; i++) {
    for (j = 0; j < arr3.length; j++) {
      if (arr3[i][j]==value) {
        return true;    
    }
  }
  return false;
}

最新更新