0

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); } 
2
  • 2
    put your code in a main method, and give it another name or prefix the classnames. Commented Nov 28, 2012 at 13:52
  • rename your class to RandomTest Commented Nov 28, 2012 at 13:53

2 Answers 2

9

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 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.