SlideShare a Scribd company logo
1 of 7
Download to read offline
Using the Coin Class
The Coin class from Listing 5.4 in the text is in the file Coin.java. Copy it to your directory, then
write a program to find the length of the longest run of heads in 100 flips of the coin. A skeleton
of the program is in the file Runs.java. To use the Coin class you need to do the following in the
program:
1. Create a coin object. 2. Inside the loop, you should use the flip method to flip the coin, the
toString method (used implicitly) to print the results of the flip, and the getFace method to see if
the result was HEADS. Keeping track of the current run length (the number of times in a row
that the coin was HEADS) and the maximum run length is an exercise in loop techniques! 3.
Print the result after the loop.
// ******************************************************************* //
Coin.java Author: Lewis and Loftus // // Represents a coin with two sides that can be flipped. //
*******************************************************************
public class Coin { public final int HEADS = 0; public final int TAILS = 1;
private int face;
// --------------------------------------------- // Sets up the coin by flipping it initially. // ----------------
----------------------------- public Coin () { flip(); }
// ----------------------------------------------- // Flips the coin by randomly choosing a face. // --------
--------------------------------------- public void flip() { face = (int) (Math.random() * 2); }
// ----------------------------------------------------- // Returns the current face of the coin as an
integer. // ----------------------------------------------------- public int getFace() { return face; }
// ---------------------------------------------------- // Returns the current face of the coin as a string. //
---------------------------------------------------- public String toString() { String faceName;
if (face == HEADS) faceName = "Heads";
Chapter 5: Conditionals and Loops 87
else faceName = "Tails";
return faceName; } }
// ******************************************************************** //
Runs.java // // Finds the length of the longest run of heads in 100 flips of a coin. //
********************************************************************
import java.util.Scanner;
public class Runs { public static void main (String[] args) { final int FLIPS = 100; // number of
coin flips
int currentRun = 0; // length of the current run of HEADS int maxRun = 0; // length of the
maximum run so far
Scanner scan = new Scanner(System.in);
// Create a coin object
// Flip the coin FLIPS times for (int i = 0; i < FLIPS; i++) { // Flip the coin & print the result
// Update the run information
}
// Print the results
} }
Solution
// *******************************************************************
// Coin.java
// Represents a coin with two sides that can be flipped.
// *******************************************************************
public class Coin
{
public final int HEADS = 0;
public final int TAILS = 1;
private int face;
// ---------------------------------------------
// Sets up the coin by flipping it initially.
// ---------------------------------------------
public Coin () { flip(); }
// -----------------------------------------------
// Flips the coin by randomly choosing a face.
// -----------------------------------------------
public void flip() { face = (int) (Math.random() * 2); }
// -----------------------------------------------------
// Returns the current face of the coin as an integer.
// -----------------------------------------------------
public int getFace() { return face; }
// ----------------------------------------------------
// Returns the current face of the coin as a string.
// ----------------------------------------------------
public String toString()
{
String faceName;
if (face == HEADS)
faceName = "Heads";
else
faceName = "Tails";
return faceName;
}
}
// ********************************************************************
// Runs.java
// Finds the length of the longest run of heads in 100 flips of a coin.
// ********************************************************************
import java.util.Scanner;
public class Runs
{
public static void main (String[] args)
{
final int FLIPS = 100; // number of coin flips
int currentRun = 0; // length of the current run of HEADS
int maxRun = 0; // length of the maximum run so far
Scanner scan = new Scanner(System.in);
// Create a coin object
Coin c = new Coin();
int face;
// Flip the coin FLIPS times
for (int i = 0; i < FLIPS; i++)
{
// Flip the coin & print the result
c.flip();
face = c.getFace();
System.out.println("Flip " + (i+1) +": " + c.toString());
if(face == 0)
currentRun++;
else
{
// Update the run information
if(currentRun > maxRun)
maxRun = currentRun;
currentRun = 0;
}
}
// Print the results
System.out.println("Maximum run of heads in a row: " + maxRun);
}
}
/*
OUTPUT:
Flip 1: Heads
Flip 2: Heads
Flip 3: Heads
Flip 4: Heads
Flip 5: Tails
Flip 6: Heads
Flip 7: Tails
Flip 8: Heads
Flip 9: Heads
Flip 10: Heads
Flip 11: Tails
Flip 12: Tails
Flip 13: Heads
Flip 14: Tails
Flip 15: Heads
Flip 16: Heads
Flip 17: Tails
Flip 18: Tails
Flip 19: Heads
Flip 20: Heads
Flip 21: Heads
Flip 22: Tails
Flip 23: Tails
Flip 24: Heads
Flip 25: Tails
Flip 26: Tails
Flip 27: Heads
Flip 28: Tails
Flip 29: Tails
Flip 30: Tails
Flip 31: Heads
Flip 32: Tails
Flip 33: Tails
Flip 34: Heads
Flip 35: Tails
Flip 36: Heads
Flip 37: Heads
Flip 38: Heads
Flip 39: Tails
Flip 40: Heads
Flip 41: Tails
Flip 42: Heads
Flip 43: Tails
Flip 44: Tails
Flip 45: Heads
Flip 46: Tails
Flip 47: Heads
Flip 48: Heads
Flip 49: Heads
Flip 50: Tails
Flip 51: Tails
Flip 52: Heads
Flip 53: Heads
Flip 54: Heads
Flip 55: Tails
Flip 56: Heads
Flip 57: Tails
Flip 58: Heads
Flip 59: Heads
Flip 60: Heads
Flip 61: Heads
Flip 62: Heads
Flip 63: Tails
Flip 64: Heads
Flip 65: Heads
Flip 66: Tails
Flip 67: Heads
Flip 68: Tails
Flip 69: Heads
Flip 70: Heads
Flip 71: Tails
Flip 72: Heads
Flip 73: Heads
Flip 74: Heads
Flip 75: Tails
Flip 76: Tails
Flip 77: Tails
Flip 78: Heads
Flip 79: Heads
Flip 80: Heads
Flip 81: Tails
Flip 82: Heads
Flip 83: Heads
Flip 84: Tails
Flip 85: Heads
Flip 86: Heads
Flip 87: Heads
Flip 88: Heads
Flip 89: Heads
Flip 90: Tails
Flip 91: Heads
Flip 92: Tails
Flip 93: Tails
Flip 94: Heads
Flip 95: Tails
Flip 96: Tails
Flip 97: Heads
Flip 98: Tails
Flip 99: Tails
Flip 100: Heads
Maximum run of heads in a row: 5
*/

More Related Content

Similar to Using the Coin Class The Coin class from Listing 5.4 in the text i.pdf

printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);Joel Porquet
 
Itsecteam shell
Itsecteam shellItsecteam shell
Itsecteam shellady36
 
Please follow the cod eand comments for description CODE #incl.pdf
Please follow the cod eand comments for description CODE #incl.pdfPlease follow the cod eand comments for description CODE #incl.pdf
Please follow the cod eand comments for description CODE #incl.pdfannaielectronicsvill
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with ExtbaseJochen Rau
 
Flex入門
Flex入門Flex入門
Flex入門dewa
 
computer notes - Data Structures - 14
computer notes - Data Structures - 14computer notes - Data Structures - 14
computer notes - Data Structures - 14ecomputernotes
 
The Ring programming language version 1.10 book - Part 16 of 212
The Ring programming language version 1.10 book - Part 16 of 212The Ring programming language version 1.10 book - Part 16 of 212
The Ring programming language version 1.10 book - Part 16 of 212Mahmoud Samir Fayed
 
C programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdfC programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdfflashfashioncasualwe
 
i need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docxi need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docxursabrooks36447
 
Scala Under the Hood / ScalaSwarm
Scala Under the Hood / ScalaSwarmScala Under the Hood / ScalaSwarm
Scala Under the Hood / ScalaSwarmTzofia Shiftan
 
R57php 1231677414471772-2
R57php 1231677414471772-2R57php 1231677414471772-2
R57php 1231677414471772-2ady36
 
RussianRouletteProgram
RussianRouletteProgramRussianRouletteProgram
RussianRouletteProgramAmy Baxter
 
ipython notebook poc memory forensics
ipython notebook poc memory forensicsipython notebook poc memory forensics
ipython notebook poc memory forensicsVincent Ohprecio
 
The Ring programming language version 1.5.3 book - Part 68 of 184
The Ring programming language version 1.5.3 book - Part 68 of 184The Ring programming language version 1.5.3 book - Part 68 of 184
The Ring programming language version 1.5.3 book - Part 68 of 184Mahmoud Samir Fayed
 

Similar to Using the Coin Class The Coin class from Listing 5.4 in the text i.pdf (20)

printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
printf("%s from %c to Z, in %d minutes!\n", "printf", 'A', 45);
 
Loop
LoopLoop
Loop
 
SUMO simulation CODES AND STEPS
SUMO simulation CODES AND STEPSSUMO simulation CODES AND STEPS
SUMO simulation CODES AND STEPS
 
Itsecteam shell
Itsecteam shellItsecteam shell
Itsecteam shell
 
Please follow the cod eand comments for description CODE #incl.pdf
Please follow the cod eand comments for description CODE #incl.pdfPlease follow the cod eand comments for description CODE #incl.pdf
Please follow the cod eand comments for description CODE #incl.pdf
 
Get into the FLOW with Extbase
Get into the FLOW with ExtbaseGet into the FLOW with Extbase
Get into the FLOW with Extbase
 
Nop2
Nop2Nop2
Nop2
 
Flex入門
Flex入門Flex入門
Flex入門
 
Di yquadricopter
Di yquadricopterDi yquadricopter
Di yquadricopter
 
computer notes - Data Structures - 14
computer notes - Data Structures - 14computer notes - Data Structures - 14
computer notes - Data Structures - 14
 
The Ring programming language version 1.10 book - Part 16 of 212
The Ring programming language version 1.10 book - Part 16 of 212The Ring programming language version 1.10 book - Part 16 of 212
The Ring programming language version 1.10 book - Part 16 of 212
 
C programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdfC programming tweak needed for a specific program.This is the comp.pdf
C programming tweak needed for a specific program.This is the comp.pdf
 
i need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docxi need an input of this program.  anything good or bad.  what could .docx
i need an input of this program.  anything good or bad.  what could .docx
 
Sbaw091110
Sbaw091110Sbaw091110
Sbaw091110
 
Scala Under the Hood / ScalaSwarm
Scala Under the Hood / ScalaSwarmScala Under the Hood / ScalaSwarm
Scala Under the Hood / ScalaSwarm
 
R57php 1231677414471772-2
R57php 1231677414471772-2R57php 1231677414471772-2
R57php 1231677414471772-2
 
RussianRouletteProgram
RussianRouletteProgramRussianRouletteProgram
RussianRouletteProgram
 
Custom keys
Custom keysCustom keys
Custom keys
 
ipython notebook poc memory forensics
ipython notebook poc memory forensicsipython notebook poc memory forensics
ipython notebook poc memory forensics
 
The Ring programming language version 1.5.3 book - Part 68 of 184
The Ring programming language version 1.5.3 book - Part 68 of 184The Ring programming language version 1.5.3 book - Part 68 of 184
The Ring programming language version 1.5.3 book - Part 68 of 184
 

More from anandastores

You have been made the GIS Manager for “Texas Infrastructures”. The .pdf
You have been made the GIS Manager for “Texas Infrastructures”. The .pdfYou have been made the GIS Manager for “Texas Infrastructures”. The .pdf
You have been made the GIS Manager for “Texas Infrastructures”. The .pdfanandastores
 
V. A florist has roses, carnations, lilies, and snapdragons in stock.pdf
V. A florist has roses, carnations, lilies, and snapdragons in stock.pdfV. A florist has roses, carnations, lilies, and snapdragons in stock.pdf
V. A florist has roses, carnations, lilies, and snapdragons in stock.pdfanandastores
 
utilization of computers and the subsequent increase in gethering of.pdf
utilization of computers and the subsequent increase in gethering of.pdfutilization of computers and the subsequent increase in gethering of.pdf
utilization of computers and the subsequent increase in gethering of.pdfanandastores
 
Using two independent samples, we test for a hypothesized difference.pdf
Using two independent samples, we test for a hypothesized difference.pdfUsing two independent samples, we test for a hypothesized difference.pdf
Using two independent samples, we test for a hypothesized difference.pdfanandastores
 
Using Tichys 3 Types of Change approaches how can this be useful t.pdf
Using Tichys 3 Types of Change approaches how can this be useful t.pdfUsing Tichys 3 Types of Change approaches how can this be useful t.pdf
Using Tichys 3 Types of Change approaches how can this be useful t.pdfanandastores
 
Using the two-phase method, solve the following LP problem. Then ver.pdf
Using the two-phase method, solve the following LP problem. Then ver.pdfUsing the two-phase method, solve the following LP problem. Then ver.pdf
Using the two-phase method, solve the following LP problem. Then ver.pdfanandastores
 
Using the text Appendix concerning HofstedeSolutionBahrainPo.pdf
Using the text Appendix concerning HofstedeSolutionBahrainPo.pdfUsing the text Appendix concerning HofstedeSolutionBahrainPo.pdf
Using the text Appendix concerning HofstedeSolutionBahrainPo.pdfanandastores
 
Using the Shifting property of unit impulse, prove thatSolution.pdf
Using the Shifting property of unit impulse, prove thatSolution.pdfUsing the Shifting property of unit impulse, prove thatSolution.pdf
Using the Shifting property of unit impulse, prove thatSolution.pdfanandastores
 
Using the OCI instrument online, and the cultural change background .pdf
Using the OCI instrument online, and the cultural change background .pdfUsing the OCI instrument online, and the cultural change background .pdf
Using the OCI instrument online, and the cultural change background .pdfanandastores
 
Using the Hofstede model, discuss the differences in power distance,.pdf
Using the Hofstede model, discuss the differences in power distance,.pdfUsing the Hofstede model, discuss the differences in power distance,.pdf
Using the Hofstede model, discuss the differences in power distance,.pdfanandastores
 
Using implicit differentiation, I gotIn order for the tangent line.pdf
Using implicit differentiation, I gotIn order for the tangent line.pdfUsing implicit differentiation, I gotIn order for the tangent line.pdf
Using implicit differentiation, I gotIn order for the tangent line.pdfanandastores
 
Using the data set below, please calculate the find the median 10.pdf
Using the data set below, please calculate the find the median 10.pdfUsing the data set below, please calculate the find the median 10.pdf
Using the data set below, please calculate the find the median 10.pdfanandastores
 
Using the data below, I need answers to the following questionsa).pdf
Using the data below, I need answers to the following questionsa).pdfUsing the data below, I need answers to the following questionsa).pdf
Using the data below, I need answers to the following questionsa).pdfanandastores
 
Using the data set below, please calculate the find the mode 10 1.pdf
Using the data set below, please calculate the find the mode 10 1.pdfUsing the data set below, please calculate the find the mode 10 1.pdf
Using the data set below, please calculate the find the mode 10 1.pdfanandastores
 
Using the current policy on immigration, analyze the overall manner .pdf
Using the current policy on immigration, analyze the overall manner .pdfUsing the current policy on immigration, analyze the overall manner .pdf
Using the current policy on immigration, analyze the overall manner .pdfanandastores
 
Using the bottom-up, or participatory approach a. budgets are first .pdf
Using the bottom-up, or participatory approach a. budgets are first .pdfUsing the bottom-up, or participatory approach a. budgets are first .pdf
Using the bottom-up, or participatory approach a. budgets are first .pdfanandastores
 
Using non-zero whole numbers there is just one combination of two nu.pdf
Using non-zero whole numbers there is just one combination of two nu.pdfUsing non-zero whole numbers there is just one combination of two nu.pdf
Using non-zero whole numbers there is just one combination of two nu.pdfanandastores
 
Using lists (bullets and numbers) in documentsA. should be avoided.pdf
Using lists (bullets and numbers) in documentsA. should be avoided.pdfUsing lists (bullets and numbers) in documentsA. should be avoided.pdf
Using lists (bullets and numbers) in documentsA. should be avoided.pdfanandastores
 
Using scientific notation, show that it takes light from the Sun abo.pdf
Using scientific notation, show that it takes light from the Sun abo.pdfUsing scientific notation, show that it takes light from the Sun abo.pdf
Using scientific notation, show that it takes light from the Sun abo.pdfanandastores
 

More from anandastores (19)

You have been made the GIS Manager for “Texas Infrastructures”. The .pdf
You have been made the GIS Manager for “Texas Infrastructures”. The .pdfYou have been made the GIS Manager for “Texas Infrastructures”. The .pdf
You have been made the GIS Manager for “Texas Infrastructures”. The .pdf
 
V. A florist has roses, carnations, lilies, and snapdragons in stock.pdf
V. A florist has roses, carnations, lilies, and snapdragons in stock.pdfV. A florist has roses, carnations, lilies, and snapdragons in stock.pdf
V. A florist has roses, carnations, lilies, and snapdragons in stock.pdf
 
utilization of computers and the subsequent increase in gethering of.pdf
utilization of computers and the subsequent increase in gethering of.pdfutilization of computers and the subsequent increase in gethering of.pdf
utilization of computers and the subsequent increase in gethering of.pdf
 
Using two independent samples, we test for a hypothesized difference.pdf
Using two independent samples, we test for a hypothesized difference.pdfUsing two independent samples, we test for a hypothesized difference.pdf
Using two independent samples, we test for a hypothesized difference.pdf
 
Using Tichys 3 Types of Change approaches how can this be useful t.pdf
Using Tichys 3 Types of Change approaches how can this be useful t.pdfUsing Tichys 3 Types of Change approaches how can this be useful t.pdf
Using Tichys 3 Types of Change approaches how can this be useful t.pdf
 
Using the two-phase method, solve the following LP problem. Then ver.pdf
Using the two-phase method, solve the following LP problem. Then ver.pdfUsing the two-phase method, solve the following LP problem. Then ver.pdf
Using the two-phase method, solve the following LP problem. Then ver.pdf
 
Using the text Appendix concerning HofstedeSolutionBahrainPo.pdf
Using the text Appendix concerning HofstedeSolutionBahrainPo.pdfUsing the text Appendix concerning HofstedeSolutionBahrainPo.pdf
Using the text Appendix concerning HofstedeSolutionBahrainPo.pdf
 
Using the Shifting property of unit impulse, prove thatSolution.pdf
Using the Shifting property of unit impulse, prove thatSolution.pdfUsing the Shifting property of unit impulse, prove thatSolution.pdf
Using the Shifting property of unit impulse, prove thatSolution.pdf
 
Using the OCI instrument online, and the cultural change background .pdf
Using the OCI instrument online, and the cultural change background .pdfUsing the OCI instrument online, and the cultural change background .pdf
Using the OCI instrument online, and the cultural change background .pdf
 
Using the Hofstede model, discuss the differences in power distance,.pdf
Using the Hofstede model, discuss the differences in power distance,.pdfUsing the Hofstede model, discuss the differences in power distance,.pdf
Using the Hofstede model, discuss the differences in power distance,.pdf
 
Using implicit differentiation, I gotIn order for the tangent line.pdf
Using implicit differentiation, I gotIn order for the tangent line.pdfUsing implicit differentiation, I gotIn order for the tangent line.pdf
Using implicit differentiation, I gotIn order for the tangent line.pdf
 
Using the data set below, please calculate the find the median 10.pdf
Using the data set below, please calculate the find the median 10.pdfUsing the data set below, please calculate the find the median 10.pdf
Using the data set below, please calculate the find the median 10.pdf
 
Using the data below, I need answers to the following questionsa).pdf
Using the data below, I need answers to the following questionsa).pdfUsing the data below, I need answers to the following questionsa).pdf
Using the data below, I need answers to the following questionsa).pdf
 
Using the data set below, please calculate the find the mode 10 1.pdf
Using the data set below, please calculate the find the mode 10 1.pdfUsing the data set below, please calculate the find the mode 10 1.pdf
Using the data set below, please calculate the find the mode 10 1.pdf
 
Using the current policy on immigration, analyze the overall manner .pdf
Using the current policy on immigration, analyze the overall manner .pdfUsing the current policy on immigration, analyze the overall manner .pdf
Using the current policy on immigration, analyze the overall manner .pdf
 
Using the bottom-up, or participatory approach a. budgets are first .pdf
Using the bottom-up, or participatory approach a. budgets are first .pdfUsing the bottom-up, or participatory approach a. budgets are first .pdf
Using the bottom-up, or participatory approach a. budgets are first .pdf
 
Using non-zero whole numbers there is just one combination of two nu.pdf
Using non-zero whole numbers there is just one combination of two nu.pdfUsing non-zero whole numbers there is just one combination of two nu.pdf
Using non-zero whole numbers there is just one combination of two nu.pdf
 
Using lists (bullets and numbers) in documentsA. should be avoided.pdf
Using lists (bullets and numbers) in documentsA. should be avoided.pdfUsing lists (bullets and numbers) in documentsA. should be avoided.pdf
Using lists (bullets and numbers) in documentsA. should be avoided.pdf
 
Using scientific notation, show that it takes light from the Sun abo.pdf
Using scientific notation, show that it takes light from the Sun abo.pdfUsing scientific notation, show that it takes light from the Sun abo.pdf
Using scientific notation, show that it takes light from the Sun abo.pdf
 

Recently uploaded

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIShubhangi Sonawane
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 

Recently uploaded (20)

ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 

Using the Coin Class The Coin class from Listing 5.4 in the text i.pdf

  • 1. Using the Coin Class The Coin class from Listing 5.4 in the text is in the file Coin.java. Copy it to your directory, then write a program to find the length of the longest run of heads in 100 flips of the coin. A skeleton of the program is in the file Runs.java. To use the Coin class you need to do the following in the program: 1. Create a coin object. 2. Inside the loop, you should use the flip method to flip the coin, the toString method (used implicitly) to print the results of the flip, and the getFace method to see if the result was HEADS. Keeping track of the current run length (the number of times in a row that the coin was HEADS) and the maximum run length is an exercise in loop techniques! 3. Print the result after the loop. // ******************************************************************* // Coin.java Author: Lewis and Loftus // // Represents a coin with two sides that can be flipped. // ******************************************************************* public class Coin { public final int HEADS = 0; public final int TAILS = 1; private int face; // --------------------------------------------- // Sets up the coin by flipping it initially. // ---------------- ----------------------------- public Coin () { flip(); } // ----------------------------------------------- // Flips the coin by randomly choosing a face. // -------- --------------------------------------- public void flip() { face = (int) (Math.random() * 2); } // ----------------------------------------------------- // Returns the current face of the coin as an integer. // ----------------------------------------------------- public int getFace() { return face; } // ---------------------------------------------------- // Returns the current face of the coin as a string. // ---------------------------------------------------- public String toString() { String faceName; if (face == HEADS) faceName = "Heads"; Chapter 5: Conditionals and Loops 87 else faceName = "Tails"; return faceName; } } // ******************************************************************** // Runs.java // // Finds the length of the longest run of heads in 100 flips of a coin. // ******************************************************************** import java.util.Scanner; public class Runs { public static void main (String[] args) { final int FLIPS = 100; // number of coin flips int currentRun = 0; // length of the current run of HEADS int maxRun = 0; // length of the maximum run so far
  • 2. Scanner scan = new Scanner(System.in); // Create a coin object // Flip the coin FLIPS times for (int i = 0; i < FLIPS; i++) { // Flip the coin & print the result // Update the run information } // Print the results } } Solution // ******************************************************************* // Coin.java // Represents a coin with two sides that can be flipped. // ******************************************************************* public class Coin { public final int HEADS = 0; public final int TAILS = 1; private int face; // --------------------------------------------- // Sets up the coin by flipping it initially. // --------------------------------------------- public Coin () { flip(); } // ----------------------------------------------- // Flips the coin by randomly choosing a face. // ----------------------------------------------- public void flip() { face = (int) (Math.random() * 2); } // ----------------------------------------------------- // Returns the current face of the coin as an integer. // ----------------------------------------------------- public int getFace() { return face; } // ---------------------------------------------------- // Returns the current face of the coin as a string. // ---------------------------------------------------- public String toString()
  • 3. { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; } } // ******************************************************************** // Runs.java // Finds the length of the longest run of heads in 100 flips of a coin. // ******************************************************************** import java.util.Scanner; public class Runs { public static void main (String[] args) { final int FLIPS = 100; // number of coin flips int currentRun = 0; // length of the current run of HEADS int maxRun = 0; // length of the maximum run so far Scanner scan = new Scanner(System.in); // Create a coin object Coin c = new Coin(); int face; // Flip the coin FLIPS times for (int i = 0; i < FLIPS; i++) { // Flip the coin & print the result c.flip(); face = c.getFace(); System.out.println("Flip " + (i+1) +": " + c.toString()); if(face == 0)
  • 4. currentRun++; else { // Update the run information if(currentRun > maxRun) maxRun = currentRun; currentRun = 0; } } // Print the results System.out.println("Maximum run of heads in a row: " + maxRun); } } /* OUTPUT: Flip 1: Heads Flip 2: Heads Flip 3: Heads Flip 4: Heads Flip 5: Tails Flip 6: Heads Flip 7: Tails Flip 8: Heads Flip 9: Heads Flip 10: Heads Flip 11: Tails Flip 12: Tails Flip 13: Heads Flip 14: Tails Flip 15: Heads Flip 16: Heads
  • 5. Flip 17: Tails Flip 18: Tails Flip 19: Heads Flip 20: Heads Flip 21: Heads Flip 22: Tails Flip 23: Tails Flip 24: Heads Flip 25: Tails Flip 26: Tails Flip 27: Heads Flip 28: Tails Flip 29: Tails Flip 30: Tails Flip 31: Heads Flip 32: Tails Flip 33: Tails Flip 34: Heads Flip 35: Tails Flip 36: Heads Flip 37: Heads Flip 38: Heads Flip 39: Tails Flip 40: Heads Flip 41: Tails Flip 42: Heads Flip 43: Tails Flip 44: Tails Flip 45: Heads Flip 46: Tails Flip 47: Heads Flip 48: Heads Flip 49: Heads Flip 50: Tails Flip 51: Tails Flip 52: Heads
  • 6. Flip 53: Heads Flip 54: Heads Flip 55: Tails Flip 56: Heads Flip 57: Tails Flip 58: Heads Flip 59: Heads Flip 60: Heads Flip 61: Heads Flip 62: Heads Flip 63: Tails Flip 64: Heads Flip 65: Heads Flip 66: Tails Flip 67: Heads Flip 68: Tails Flip 69: Heads Flip 70: Heads Flip 71: Tails Flip 72: Heads Flip 73: Heads Flip 74: Heads Flip 75: Tails Flip 76: Tails Flip 77: Tails Flip 78: Heads Flip 79: Heads Flip 80: Heads Flip 81: Tails Flip 82: Heads Flip 83: Heads Flip 84: Tails Flip 85: Heads Flip 86: Heads Flip 87: Heads Flip 88: Heads
  • 7. Flip 89: Heads Flip 90: Tails Flip 91: Heads Flip 92: Tails Flip 93: Tails Flip 94: Heads Flip 95: Tails Flip 96: Tails Flip 97: Heads Flip 98: Tails Flip 99: Tails Flip 100: Heads Maximum run of heads in a row: 5 */