在二维数组中只打印一次随机数



我试图只打印一次从1到15的随机数的2D数组。我已经能够打印出数组,但只能按顺序打印。

int x =0;
public void Numberbox(){
            int[][] a2 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,x}};
  String output = "";   // Accumulate text here (should be StringBuilder).
//... Print array in rectangular form using nested for loops.
for (int row = 0; row < ROWS; row++) 
{
for (int col = 0; col < COLS; col++) 
{
output += " " + a2[row][col];
}
output += "n";
}
    System.out.print(output);

}

您可以使用集合,例如列表,并使用内置的shuffle函数。例如:

public static void main(String... args) throws Exception {
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < 16; i++) {
        list.add(i);
    }
    System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    Collections.shuffle(list);
    System.out.println(list); //[11, 5, 10, 9, 7, 0, 6, 1, 3, 14, 2, 4, 15, 13, 12, 8]
    int[][] a2 = new int[4][4];
    for (int i = 0; i < 4; i++) {
        for (int j = 0;  j< 4; j++) {
            a2[i][j] = list.get(i*4 + j);
        }
    }
    System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3, 14, 2, 4], [15, 13, 12, 8]]
}

我认为您应该使用Collections.shuffle()来达到您的目的。

在内部循环中使用Random.nextInt()生成随机数:

public class RandomGrid
{
    public static void main(String[] args)
    {
        Random r = new Random();
        int ROWS = 4;
        int COLS = 3;
        String output = ""; // Accumulate text here (should be StringBuilder).
        for (int row = 0; row < ROWS; row++)
        {
            for (int col = 0; col < COLS; col++)
            {
                output += " " + r.nextInt(16);
            }
            output += "n";
        }
        System.out.print(output);
    }
}

示例输出:

 12 9 10
 8 7 3
 8 10 11
 15 14 3

最新更新