0

So the question for my assignment is "Produce a horizontal star line that show your 10 variables from top to bottom as individual, distinct stars varying based on its value. For example, random number is 4, so I will have ****.

This is what I did so far

import java.util.*;
public class Problem01 {
    public static void main(String[] args){
        //create random integer
        Random ran = new Random();
        for (int i = 1; i <=10; i++ ){
            int random = ran.nextInt(20);
            //Printing the random number
            System.out.println("Number " + "(" + random + "): ");
        }
    }
}

I can generate 10 random number but I don't know how generate the stars, can you guys help me, thanks a lot.

smac89
  • 39,374
  • 15
  • 132
  • 179
Peter
  • 61
  • 5

2 Answers2

0
private static String generateStars(final int numberOfStars) {
   final StringBuilder sb = new StringBuilder(numberOfStars);
   for (int i = 1; i <= n; i++) {
      sb.append("*");
   } 
   return sb.toString();
}
Autocrab
  • 3,474
  • 1
  • 15
  • 15
  • This is only code. Youn intended to make your answer more upvotable by adding an explanation, didn't you? – Yunnosch Sep 17 '20 at 04:29
  • Thanks a lot, but I'm a newbie in Java so I don't really understand the code, I currently just started on loops so your code look a little complicated for me to understand – Peter Sep 17 '20 at 04:32
  • Strings addition are working differ than number addition. If your write 1 + 1, the result will be 2, but if you write "1" + "1" the result will be "11". Its called concatenation. So in this function we concatenate "*" with numberOfStars times. We use helper class StringBuilder, which is more efficient to build Strings. – Autocrab Sep 17 '20 at 04:37
  • [Please read [How to anwser](https://stackoverflow.com/help/how-to-answer) Edit your answer and explain why it is the solution the the question. – Linda Lawton - DaImTo Sep 17 '20 at 06:59
0
import java.util.*;
public class Problem01 {
    public static void main(String[] args){
        //create random integer
        Random ran = new Random();
        for (int i = 1; i <=10; i++ ){
            int random = ran.nextInt(20);
            //Printing the random number
            System.out.println("Number " + "(" + random + "): ");
            
            for(int j = 1; j <= random; j++)
            {
                System.out.print("*");
            }
            System.out.println();
            
            
        }
    }
}

Sample output

Number (0):

Number (6):
******
Number (8):
********
Number (18):
******************
Number (17):
*****************
Number (0):

Number (7):
*******
Number (10):
**********
Number (14):
**************
Number (8):
********
Abdullah Leghari
  • 2,332
  • 3
  • 24
  • 40