Chapter 5a - Random
Random Introductionβ
import java.util.Random;
class Main {
public static void main(String args[]) {
Random rand = new Random(); //creates object of class Random which is used to generate random number
int randomNum = rand.nextInt(4); //generates random numbers
System.out.println(randomNum);
}
}
π§ͺ Try the code out~!
Coin Simulationβ
import java.util.Scanner;
import java.util.Random;
class Main {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
Random rand = new Random(); //creates object of class Random which is used to generate random number
System.out.println("This is a simulation of a coin toss.");
System.out.println("Tossing coin now...\n");
int randomNum = rand.nextInt(2); //generates random numbers 0 & 1
if (randomNum == 0) {
System.out.println("HEADS...\n");
} else {
System.out.println("TAILS...\n");
}
}
}
π§ͺ Try the code out~!
(i) Does the user provide any input here?
(ii) What are the possible outputs?
(iii) Which line of code requires that the random module be imported?
(iv) What are the values stored by randomNum ?
(v) What module is required to generate random numbers?
Exercise: Team Selectionβ
tip
- Create a program to randomnly assign someone in either blue or red team
πββοΈ expected
Introduce Random Module - Formattingβ
import java.math.RoundingMode;
import java.text.DecimalFormat;
class Main {
public static void main(String[] args) {
for(int count = 0; count< 5; count++){
System.out.println(Math.random());
}
}
}
π§ͺ Try the code out~!
Formatting Randomβ
import java.math.RoundingMode;
import java.text.DecimalFormat;
class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.00");
for(int count = 0; count< 5; count++){
double d=Math.random();
System.out.println(df.format(d));
}
}
}