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​