Random value
In this chapter you will learn:
Random integers
Call nextInt() to get random integers
import java.util.Random;
//from j ava2s. c o m
public class MainClass {
public static void main(String args[]) {
Random generator = new Random();
for(int i = 0; i < 10; i++)
System.out.println(generator.nextInt());
}
}
The code above generates the following result.
Random double
call nextDouble() to get next random double value
import java.util.Random;
/*ja v a 2 s . c om*/
public class MainClass {
public static void main(String args[]) {
Random rand = new Random();
System.out.println(rand.nextDouble());
}
}
The code above generates the following result.
Seed a random
The next example creates Random class from an Integer using new Random(int intValue).
import java.util.Random;
//from j a v a 2 s . com
public class MainClass {
public static void main(String args[]) {
Random generator = new Random(100);
System.out.println("First generator:");
for(int i = 0; i < 10; i++)
System.out.println(generator.nextInt());
}
}
Output:
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Utility Classes