要使用随机字母填充2d数组,请使用Random类。我们首先声明一个二维数组-
char arr[][] = new char[3][3];
现在,在嵌套的for循环中,使用Random类对象根据switch的大小写获取随机值。在这里,我们的范围是3,即一次包含3个字母的集合-
Random randNum = new Random(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int x = randNum.nextInt(3); switch (x) { case 0: { arr[i][j] = 'p'; break; } case 1: { arr[i][j] = 'q'; break; } . . . } } }
现在,对于范围为3的随机字母的字符串表示形式-
Arrays.deepToString(arr)
import java.util.Arrays; import java.util.Random; public class Demo { public static void main(String[] args) { char arr[][] = new char[3][3]; Random randNum = new Random(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int x = randNum.nextInt(3); switch (x) { case 0: { arr[i][j] = 'p'; break; } case 1: { arr[i][j] = 'q'; break; } case 2: { arr[i][j] = 'r'; break; } case 3: { arr[i][j] = 's'; break; } case 4: { arr[i][j] = 't'; break; } case 5: { arr[i][j] = 'u'; break; } case 6: { arr[i][j] = 'v'; break; } case 7: { arr[i][j] = 'w'; break; } } } } System.out.println("Random alphabets..."); System.out.println(Arrays.deepToString(arr)); } }
输出结果
Random alphabets... [[q, q, p], [p, p, q], [p, p, p]]