简体   繁体   中英

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);
    }

You should use unique class names unless you feel like referring to the different Random s 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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM