Karim Wagdy Karim Wagdy - 1 month ago 7
Java Question

random number = the same number of stars

i have an assignment to do , all i have to do is write a code in a button, when you click the button a 2 random numbers between 1-10 will appear in one message and i wrote this code

Random r=new Random();
String total = "";
for (int z=0;z<5;z=z+1) {
int x=r.nextInt(10);
total = total+x+"\n";
}
JOptionPane.showMessageDialog(null,total);


my problem now is when the message appear i need to put a stars in front of each random number. for example :
i clicked the button, the message appeared, a 5 random numbers appeared like

5
2
3
4
8


i need to write a code to put stars equal each random number like

5 *****
2 **
3 ***
4 ****
8 ********


so, is there any simple code to make this happened ?

p.s : i'm a java beginner so i need a simple code so i can understand it.
thanks for your help :)

Answer

For this you can just create a variable that has 10 *'s then for each time you grab a random number you can use substring(0, [random number]); for the print out.

I haven't run this code, but this should do what you want it to do.

Random r=new Random();

String stars = "**********";
String total = "";
for (int z=0;z<5;z=z+1) {
    int x=1+r.nextInt(9);
    total = total+x+stars.substring(0, x)"\n";
}
JOptionPane.showMessageDialog(null,total);

If you just wanted to use loops. I believe this is the code:

Random r=new Random();

String stars = "";
String total = "";
for (int z=0;z<5;z=z+1) {
    stars = "";
    int x=1+r.nextInt(9);
    for(int i=0; i<x; i++)
    {
        stars = stars + "*";
    }
    total = total+x+stars"\n";
}
JOptionPane.showMessageDialog(null,total);
Comments