apkos99
apkos99

Reputation: 109

How can I generate random integers in java?

How can I generate random integers and then print them?

I have tried the following code,but it does not compile.

    import java.util.Random;
    class Random
    {
        Random rand = new Random(); 
        int num=rand.nextInt(40);
        System.out.println(num);
    }

Upvotes: 0

Views: 230

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172608

You can try something like this:-

 Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
  int randomInt = randomGenerator.nextInt(100);
  log("Generated : " + randomInt);
}

Upvotes: 1

lynks
lynks

Reputation: 5689

You should use unique class names unless you feel like referring to the different Randoms by their full package titles.

import java.util.Random;

public class MyRandom {
   public static void main(String args[]) {
      Random rand = new Random(); 
      int num = rand.nextInt(40);
      System.out.println(num);
   }
}

Save the above as MyRandom.java, then do a;

javac MyRandom.java
java MyRandom

Upvotes: 9

Related Questions