使用唯一(非随机)值填充2D数组

时间:2018-07-11 22:07:29

标签: java multidimensional-array

有没有一种方法可以用唯一的非随机值填充2D数组?编译器将不允许类似以下内容:

int[][] myArray=new int[5][5];

myArray[0]=new int[] {2, 1, 1, 1, 1};

确实发生了,我在此看到的所有教程都与添加随机数或从一开始就填充数组有关(不适用于我,因为我的程序取决于用户输入才能知道要添加的数字值) )。如果这不可能,那我应该使用另一种方法吗?

2 个答案:

答案 0 :(得分:0)

您应该使用嵌套的for循环:

for(i=0;i<arr.lenght;i++)
   for(j=0;j<arr.lenght;j++)

执行嵌套循环后,添加以下内容:     myArray [i] [j] = userInput.next(); //假设您正在使用Scanner类

嵌套循环的作用是遍历数组具有的每个“空格”,并且由于您每次都要求用户输入某些内容,因此数组将在每个“空格”中填充所需的输入。

希望这会有所帮助。(忽略我的编辑,完全误读)

答案 1 :(得分:0)

您可以在整个2D整数(int)数组中填充整个数组中的唯一值,或者仅在数组的每一行中使用唯一值。有几种方法可以执行此类操作,但我们只会坚持使用基本方法。该代码是很好的注释:

  

用户仅使用唯一行填充2D整数数组:

    // Setup for Keyboard input to Console.
    Scanner input = new Scanner(System.in); 

    // System Line Separator used in console display.
    String ls = System.lineSeparator();
    // Declare and initialize a 2D Object Array.
    // We need to use Object so that all initialized
    // elements will be null rather than 0 since 0
    // could be supplied and will need to be checked
    // for Unique. Since a 2D int array by default 
    // initializes all elements to 0, a supplied 0
    // will never be considered Unique. 
    Object[][] myArray = new Object[5][5];

    // Have User fill our 2D Array...
    for (int row = 0; row < myArray.length; row++) {
        // Display the Row User will be on to fill.
        System.out.println(ls + "Enter values for Row #" + (row+1) + 
                           " of " + myArray.length);

        // Allow User to fill each column of the current Row...
        for (int column = 0; column < myArray[row].length; column++) {
            // Flag to indicate Uniqueness.
            boolean unique = false; 
            // Integer variable to hold what the User enters in console
            int value = 0;
            // Continue looping to ensure the User supplied a proper 
            // integer value which is unique to the current 2D Array
            // Row only.
            while (!unique) {
                // Display the Column User will be on to fill.
                System.out.print("Column #" + (column+1) + " value: --> ");
                // Trap User entries that are not Integer values. If any alpha
                // characters are supplied with the value then an exception is
                // automatically thrown which we trap.
                try {
                    // Get input from User...
                    value = input.nextInt(); 
                } catch (Exception ex) {
                    // Inform the User of an improper entry if an exception was thrown.
                    System.err.println("You must supply an Integer value. Try again...");
                    input.nextLine();  // Clear Scanner buffer
                    // Allow User to try another entry for the same Column
                    continue;   
                }

                // See if the supplied value is already contained within the 
                // current array Row...
                for (int j = 0; j < myArray[row].length; j++) {
                    // Stop checking if we hit null. Nothing there yet.
                    if (myArray[row][j] == null) { 
                        unique = true; 
                        break; 
                    }
                    // If a row's column element equals supplied value...
                    else if ((int)myArray[row][j] == value) { 
                        // Value is not Unique
                        unique = false;
                        System.err.println("Value is not unique to Row #" + 
                                           (row+1) + " - Try Again...");
                        break; // Break out of checking early
                    }
                    // The supplied value is unique.
                    else { 
                        unique = true; 
                    }
                }
            }
            //Place the value into the current 
            // Column for the current Row
            myArray[row][column] = value;
        }
    }

    // Convert the 2D Object Array to a 2D int Array
    int[][] intArray = new int[myArray.length][myArray[0].length];
    for (int i = 0;i < myArray.length; i++) {
        for (int j = 0; j < myArray[i].length; j++) {
            intArray[i][j] = (int)myArray[i][j]; // Cast to int
        }
    }

    // Display the 2D Array in Console Window...
    System.out.println(ls + "2D Integer Array Contents:");
    for (int i = 0; i < intArray.length; i++) {
        System.out.println("Row #" + (i+1) + ":  " + Arrays.toString(intArray[i]));
    }
}
  

用户在整个数组中使用唯一值填充2D整数数组:

// Setup for Keyboard input to Console.
Scanner input = new Scanner(System.in);
// System Line Separator used in console display.
String ls = System.lineSeparator();
// Declare and initialize a 2D Object Array.
// We need to use Object so that all initialized
// elements will be null rather than 0 since 0
// could be supplied and will need to be checked
// for Unique. Since a 2D int array by default 
// initializes all elements to 0, a supplied 0
// will never be considered Unique. 
Object[][] myArray = new Object[5][5];

// Have User fill our 2D Array...
for (int row = 0; row < myArray.length; row++) {
    // Display the Row User will be on to fill.
    System.out.println(ls + "Enter values for Row #" + (row+1) + 
                        " of " + myArray.length);

    // Allow User to fill each column of the current Row...
    for (int column = 0; column < myArray[row].length; column++) {
        // Flag to indicate Uniqueness.
        boolean unique = false;
        // Integer variable to hold what the User enters in console
        int value = 0;
        // Continue looping to ensure the User supplied a proper 
        // integer value which is unique to the ENTIRE 2D Array.
        while (!unique) {
            // Display the Column User will be on to fill.
            System.out.print("Column #" + (column+1) + " value: --> ");
            // Trap User entries that are not Integer values. If any alpha
            // characters are supplied with the value then an exception is
            // automatically thrown which we trap.
            try {
                // Get input from User...
                value = input.nextInt(); 
            } catch (Exception ex) {
                // Inform the User of an improper entry if an exception was thrown.
                System.err.println("You must supply an Integer value. Try again...");
                input.nextLine();  // Clear Scanner buffer
                // Allow User to try another entry for the same Column
                continue;
            }
            // Flag to hold when a match is found. This flag will allow 
            // us to break out the the for loops faster
            boolean match = false;
           // See if value is already contained within the array.
           // Iterate Rows...
           for (int i = 0; i < myArray.length; i++) {
                // Iterate the Columns for each Row...
                for (int j = 0; j < myArray[i].length; j++) {
                    // Stop checking if we hit null. Nothing there yet.
                    if (myArray[i][j] == null) { 
                        break; 
                    }
                    // If a row's column element equals supplied value...
                    else if ((int)myArray[i][j] == value) { 
                        match = true;  // A match was detected - Not Unique
                        System.err.println("Value is not Unique - Try Again...");
                        break;      // Break out of checking early
                    }
                }
                if (match) { break; } // Break out of outer loop is there was a match
            }
            unique = !match;  // unique flag is to be oposite of what match contains
        }
        myArray[row][column] = value; // Add supplied value to array
    }
}

// Convert the 2D Object Array to a 2D int Array
int[][] intArray = new int[myArray.length][myArray[0].length];
for (int i = 0;i < myArray.length; i++) {
   for (int j = 0; j < myArray[i].length; j++) {
       intArray[i][j] = (int)myArray[i][j]; // Cast to int
   }
}

// Display the 2D Array...
System.out.println(ls + "2D Integer Array Contents:");
for (int i = 0; i < intArray.length; i++) {
     System.out.println("Row #" + (i+1) + ":  " + Arrays.toString(intArray[i]));
}