处理一个问题,要求创建一个随机生成的 100 个字符的数组(在本例中为 " *
"(。字符的总和必须是100,并且必须打印在10行上,其中每行打印随机数量的"*
",但末尾的字符总数("*
"(必须为100。我刚开始对Java非常陌生。到目前为止,我已经得到了以下内容,需要帮助。
下面是一个示例输出和我到目前为止的代码:
输出:
0 |*******
1 |*********
2 |***************
3 |*******
4 |******************
5 |*******
6 |****************
7 |*****
8 |****
9 |************
法典:
import java.util.Scanner;
import java.util.Random;
public class ArrayTest{
public static void main(String [] args){
// The for loop to ensure there is a total of 10 rows
for(int a=0; a<10; a++){
Random bytes = new Random();
// Printing the '*' at random
int number = bytes.nextInt(10);
for(int b=0; b<number; b++){
for(int c=0; c<number; c++){
System.out.print("*");
}
System.out.println();
}
}
}
}
如果允许空行,您可以执行以下操作。您可以引入一个count
作为 '* 的总数,让生成的随机数作为一行的星数。打印每一行后,获取计数的剩余部分并将其传递到随机生成器中。检查下面的代码:
class ArrayTest{
public static void main(String [] args){
Random bytes = new Random(); //take this out of the loops as mentioned in the comments
int count = 100; //keep track of 100 '*'s
for(int a=0; a < 10; a++){ //limit to random 10 rows
if (count > 0) { //if count reaches 0, don't print anything
int rand = bytes.nextInt(count + 1);
for(int b=0; b < rand; b++){ //print random amount of '*'s
System.out.print("*");
--count; //decrement count for each '*' print
}
}
System.out.println(); //note the next line print is outside the inner for loop
}
}
}
这种方法的问题是,如果随机数接近 100,在前几次迭代中,最后几行将为空。
要打印至少 1 个"*":
Random bytes = new Random(); //take this out of the loops as mentioned in the comments
int count = 90; //keep track of 100 '*'s, since we anyway print 10 '*'s, keep the count to 90,
for(int a=0; a < 10; a++){ //limit to random 10 rows
System.out.print("*"); //print 1 anyway
if (count > 0) { //if count reaches 0, don't print anything
int rand = bytes.nextInt(count + 1);
for(int b=0; b < rand; b++){ //print random amount of '*'s
System.out.print("*");
--count; //decrement count for each '*' print
}
}
System.out.println(); //note the next line print is outside the inner for loop
}