Question: Hi, I need to modify this code so that: -if you used a local variable for your random object, now make it to a field
Hi, I need to modify this code so that:
-if you used a local variable for your random object, now make it to a field variable.
-Change the main method so that it askshow many times they would like to roll the die, instead of rolling 20 times.
import java.util.*; import java.util.Random; // Main class public class Main { // called function from a main class public int roll() { Random rand = new Random(); //generates the random number from 1-6 int random = (int)(Math.random() * (6 - 1 + 1) + 1);; // returns the random number return random; }
// main function public static void main(String[] args) { // creating a object Main obj = new Main(); int res = 0; double avg = 0; // runs the loop to call a function for 20 times for(int i =0;i<20;i++) { // calling a function with object res = obj.roll(); // calculating the sum avg = avg+res; // prints the random number System.out.println(res); } // calculating the Average avg = avg/20; System.out.println("The Average of Rolling Dice: "+avg); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
