-1

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 :)

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

0

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);
pkc
  • 16
  • 1
  • well, Yeah it works perfectly :D – Karim Wagdy Oct 27 '16 at 22:32
  • @KarimWagdy That code is going to produce values of 0 for x once in a while which doesn't match what you specified in your question. – Michael Krause Oct 27 '16 at 22:33
  • it works perfectly for me but as i told you i'm still beginner in java so i really dont understand what exactly is substring doing, all i know now is variables, if else statements and loops, so is there any other code to do it without using substring ? .. just two loops added together for example ? – Karim Wagdy Oct 27 '16 at 22:38
  • Oh yeah I just copied your code from the top. For numbers 1-10, you have to use x=1+r.nextInt(9); instead. – pkc Oct 27 '16 at 22:44
  • Ok but like i said before , I'm still bigenner so i can't go on with your code even though it works fine for me but i can't understand what exactly is substring you did add in this code .. so is there any possible to write this code without substring? – Karim Wagdy Oct 27 '16 at 22:51
  • yes thats what i was talking about, thanks alot man i really appreciate it :) – Karim Wagdy Oct 27 '16 at 23:06