Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Random;
- public class Coin {
- private String sideUp; /*A String named sideUp */
- int coinToss;
- String fileName="myoutput.txt";
- public void toss(){
- Random random = new Random(); /* Creates an instance of a random number*/
- coinToss=random.nextInt(2); /*0 to 1*/
- if (coinToss==1) {sideUp="Heads";
- } /*If the random number is 0, then it sets the sideUp field to "heads".*/
- else if (coinToss==0){sideUp="Tails";
- } /*If the random number is 1, then it sets the sideUp field to "tails".*/
- }
- public Coin(){/* no-argument constructor that calls the toss method*/
- toss();
- }
- public String getSideUp( ) {return sideUp;
- } /* A method named getSideUp that returns the value of the sideUp field*/
- public String showPastRun() {return fileName; /*A method named showPastRun that opens the file named myoutput.txt*/
- }
- }
- package Coin;
- import java.util.Scanner;
- import java.io.*;
- /* Author: Soren Fuerst
- Date 4/8/2020
- Assignment: # 5
- Instructor: Sergio Pisano*/
- public class Driver {
- public static void main(String[] args) throws IOException{
- int NumFacingHeads=0;
- int NumFacingTails=0;
- int totalToss=20;
- String answer;
- Coin thisCoin=new Coin(); /* Creates a new instance of the class "Coin"*/
- var in=new Scanner(System.in);
- PrintWriter outputFile = new PrintWriter(); /*reads data from the file and displays it*/
- outputFile.close();
- System.out.println("Does the past run need to be displayed ?");
- answer=in.next();
- if (answer.equals("no")) {System.out.println("Okay");}
- else if (answer.equals("yes")) {System.out.println("The first line in the file is:" + thisCoin.showPastRun() );}
- System.out.println("New Coin-Toss Simulator Run:");
- System.out.println("The initial side facing up is " + thisCoin.getSideUp()); /* Displays side that is initially facing up*/
- for (int myToss=0; myToss<20; myToss++) { /* The loops 20 times*/
- thisCoin.toss(); /* calls on the method "toss" to toss the coin*/
- if (thisCoin.getSideUp()=="Heads") {NumFacingHeads= NumFacingHeads +1; /* Keeps count of the number of Heads and the number of Tails*/
- }
- else if (thisCoin.getSideUp()=="Tails") {NumFacingTails= NumFacingTails +1;
- }
- System.out.println("Toss " + myToss + ":" + thisCoin.getSideUp()); /* displays the current side each time it is tossed*/
- }
- System.out.println("After " + totalToss+ " tosses, the number of Heads tossed is " + NumFacingHeads + " and the number of Tails tossed is " + NumFacingTails +".");
- FileOutputStream fos=new FileOutputStream(thisCoin.showPastRun()); /*stores data from output in the myoutput.txt*/
- PrintStream ps= new PrintStream(fos);
- System.setOut(ps);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement