Skip to main content

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

๐Ÿงช Try the code out~!

Exerciseโ€‹