我的问题是我不知道如何在循环中获取char。它必须是随机的,每个字符必须在循环中10次。 谢谢
public class Main {
public static void main(String[] args) {
field();
}
public static void field() {
final int WIDTH = 11;
final int HEIGHT = 18;
Random random = new Random();
char l = 'L';
char o = 'O';
char u = 'U';
for (int i = 0; i <= WIDTH * HEIGHT; i++) {
if (i % 12 == 0) {
System.out.println();
}
else {
System.out.print(".");
}
}
}
}
答案 0 :(得分:0)
您可以使用ThreadLocalRandom代替Random,因为它是对Random类的改进:
ThreadLocalRandom random = ThreadLocalRandom.current();
然后,您可以执行以下操作以获取随机字符:
System.out.println((char) random.nextInt(65, 97));
注意如何将整数转换为char。 random.nextInt(65, 97);
的范围是65到97,这是大写字母(A-Z)的ASCII范围。
和/或:
System.out.println((char) random.nextInt(97, 122));
将在ASCII范围97到122(a-z)之间打印小写字符。
答案 1 :(得分:0)
由于您要打印出一个11x18的矩阵,其中包含准确数量的随机放置的字符,因此应首先在内存中建立该矩阵,例如二维char
数组中。
由于print
方法可以直接打印一维char
数组,因此打印起来甚至很容易。
代码将如下所示:
final int WIDTH = 11;
final int HEIGHT = 18;
final int CHAR_COUNT = 10;
final char[] CHARS = { 'L', 'O', 'U' };
// Create matrix filled with '.'
char[][] matrix = new char[HEIGHT][WIDTH];
for (int i = 0; i < HEIGHT; i++)
Arrays.fill(matrix[i], '.');
// Randomly place CHAR_COUNT of each character from CHARS
Random random = new Random();
for (char ch : CHARS) {
for (int i = 0, x, y; i < CHAR_COUNT; i++) {
do {
x = random.nextInt(WIDTH);
y = random.nextInt(HEIGHT);
} while (matrix[y][x] != '.'); // Already filled, try again
matrix[y][x] = ch;
}
}
// Print matrix
for (char[] row : matrix)
System.out.println(row);
示例输出
....O....L. .U......OL. ......UO..L ..OU.L..U.U
U.........O ........... L....L..... ....O.....O
........... ........... .U....U.... ..........L
........... ....L...... ..U..U...L. ....O......
.....L..... L.......LU. ..L........ ...........
..L......O. ........... ..O.....U.. .........U.
....U...... ...O....U.. .........O. ....LU.....
......O.... ...L..U.... .......O... ........L..
..LU....... L.O....O.UL .......L..O ..L....O..L
OL.U....... U.........O ........... ......O....
.......L... L....U..... ........... U..L...OU..
...U.....O. ........... ........U.. .........O.
........O.. .....O.L... ........O.. U.......L..
..UL....... ........... ..L..L..OU. ........L..
.....O..UU. .......U... ........... .....L.O...
....O.U..U. O..OUO...OL .....O..... ...........
.........L. ........... U....U..OLO ......OU.U.
..L......LO ....U...... L.......... ...........