Joe Joe -3 years ago 155
Java Question

How to generate RANDOM amount of a SINGLE character using java.util.Random?

community.

I need help generating a random amount of a single character (the '*', to be more specific) via Java.

I need to generate 5 lines of asterisks (each ranging from 1-10 asterisks long). For example, it might look something like this:

***
*******
****
*********
***


Should I use the for loop to generate this code?

Here is what my (discombobulated) code looks like now:

public static void main(String[] args)
{

String asterisk1 = "*";
char character = '*';
int ascii = (int) character;

Random rand = new Random();
char randomAsterisk = (char) ('*' + Math.random() * ('*' ));

for (ascii = 1; ascii < 10; ascii ++)
{
System.out.println((char)character);
}
}


Any help will be greatly appreciated!

Answer Source

If you want to print 5 lines of asterisks of 1 to 10 long,try something like this:

public static void main(String[] args)
{
   Random rand = new Random();
   for ( int j = 0; j < 5; ++j)
   {
      int num = rand.nextInt(10);
      for ( int i = 0; i <= num; ++i )
      {
         System.out.print('*');
      }
      System.out.println();
   }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download