[英]Printing random numbers in a 2D array only once
I'm trying to print a 2D array of random numbers from 1 to 15 only once. 我正在尝试只打印一次从1到15的2D随机数数组。 I've been able to print out the array but only sequentially. 我已经能够打印出数组,但只能按顺序打印。
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);
}
You could use a collection, for example a list, and use the built-in shuffle function. 您可以使用一个集合,例如一个列表,并使用内置的随机播放功能。 For example: 例如:
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()
。
Use Random.nextInt()
within the inner loop to generate the random numbers: 在内部循环中使用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);
}
}
Example output: 输出示例:
12 9 10
8 7 3
8 10 11
15 14 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.