以随机方式生成阵列打印

时间:2018-01-19 05:26:53

标签: java arrays random character

处理一个问题,要求创建一个随机生成的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();
      }            

    }
  }
}

1 个答案:

答案 0 :(得分:0)

如果允许空行,您可以执行以下操作。您可以将count作为&#39; *&#39;的总数,并将生成的随机数作为一行的星数。打印完每行后,获取剩余的计数并将其传递给随机生成器。检查以下代码:

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&#39; *&#39;:

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
    }