1

The throw of a die is a popular program in Java,

public class Die {

    /*  This program simulates rolling a die */
    public static void main(String[] args) {
        int die;   // The number on the die.
        die = (int)(Math.random()*6 + 1);
        System.out.println (die);         
    } // end main()
} // end class

What I wish to do is make it repeat, 500 times. I have not been able to put this program into a loop of 500. I usually program in Python, thus I guess my Java has rusted !

Any help is most welcome !

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Arkapravo
  • 4,084
  • 9
  • 37
  • 46
  • 1
    @BalusC Did you see the part where "die" is singular and "dice" is plural? – Etaoin Apr 10 '10 at 03:59
  • @Etaoin: Oh! I always thought it was dice-dices. I'll rollback it. Many thanks for noting. – BalusC Apr 10 '10 at 04:02
  • 4
    @Arkapravo: I'm glad you decided to ask here instead of copying the code and pasting it 499 times. Good for you. – Mark Rushakoff Apr 10 '10 at 04:12
  • @Mark Rushakoff: I was actually hitting 'UP arrow' and 'Enter' in the command-line, after about 227 such attempts my fingers started to pain ! ;) – Arkapravo Apr 10 '10 at 05:05

3 Answers3

6

You can use the for statement for this. Learn more about it at this Sun tutorial.

E.g.

for (int i = 0; i < 500; i++) {
    // This will be executed 500 times.
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
6

It's a little weird to forget how to do a loop, but here's my solution:

Random r = new Random();
for (int i = 0; i < 500; ++i) {
    int die = r.nextInt(6) + 1; // integer in range [1, 6]
    System.out.println(die);
}

Notice that I use Random.nextInt() instead of Math.random(). There are several reasons for that in here

Hope that helps :)

Community
  • 1
  • 1
Phil
  • 5,595
  • 5
  • 35
  • 55
  • @Po : yeah, it is weird .... but I spent a fair amount of time and got to nothing .... guess it is the Python effect ! – Arkapravo Apr 10 '10 at 04:44
1
public class Die {
    /** This program simulates rolling a die */
    public static void main(String[] args) {

       int die;   // The number on the die.

       for(int i = 0; i < 500; i++){
           die = (int)(Math.random()*6 + 1);
           System.out.println (die);    
       }    
    }  // end main()
}  // end class
Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
Josh K
  • 28,364
  • 20
  • 86
  • 132