198k views
5 votes
Write a program segment that simulates flipping a coin 25 times by generating and displaying 25 random integers, each of which is either 1 or 2

User Xero
by
4.8k points

1 Answer

2 votes

Answer:

//import the Random class

import java.util.Random;

//Begin class definition

public class CoinFlipper {

//The main method

public static void main(String []args){

//Create an object of the Random class

Random ran = new Random();

System.out.println("Result");

//Use the object and the number of times for simulation

//to call the flipCoin method

flipCoin(ran, 25);

} //End of main method

//Method to flip coin

public static void flipCoin(Random ran, int nooftimes){

//Create a loop to run as many times as specified in variable nooftimes

for(int i=1; i<=nooftimes; i++)

System.out.println(ran.nextInt(2) + 1);

}

} //End of class definition

====================================================

Sample Output:

Result

1

1

1

2

1

2

2

1

2

1

1

2

1

2

1

1

1

2

1

1

1

2

2

1

2

========================================================

Step-by-step explanation:

The above code has been written in Java. It contains comments explaining every part of the code. Please go through the comments.

The sample output from the execution of the code is also given above.

The code is re-written as follows without comments.

import java.util.Random;

public class CoinFlipper {

public static void main(String []args){

Random ran = new Random();

System.out.println("Result");

flipCoin(ran, 25);

}

public static void flipCoin(Random ran, int nooftimes){

for(int i=1; i<=nooftimes; i++)

System.out.println(ran.nextInt(2) + 1);

}

}

User Comecme
by
4.8k points