Write a method named coinFlip that accepts as its parameter a Scanner for an inp
ID: 3555629 • Letter: W
Question
Write a method named coinFlip that accepts as its parameter a Scanner for an input file. Assume that the input file data represents results of sets of coin flips that are either heads (H) or tails (T) in either upper or lower case, separated by at least one space. Your method should consider each line to be a separate set of coin flips and should output to the console the number of heads and the percentage of heads in that line, rounded to the nearest tenth. If this percentage is more than 50%, you should print a "You win" message. For example, consider the following input file:
H T H H T
T t t T h H
h
For the input above, your method should produce the following output:
3 heads (60.0%)
You win!
2 heads (33.3%)
1 heads (100.0%)
You win!
The format of your output must exactly match that shown above. You may assume that the Scanner contains at least 1 line of input, that each line contains at least one token, and that no tokens other than h, H, t, or T will be in the lines.
Explanation / Answer
import java.io.*;
public class headtail {
public void coinFlip(FileInputStream f) throws IOException
{
int count=0;
int head=0;
int tail=0;
char b;
do
{
b=(char)f.read();
if(b=='H'||b=='h')
{
head++;
}
else
{
tail++;
}
count=count+1;
}while(f.read()!=-1);
if(head<(count/2))
{
System.out.println(head+" Heads");
System.out.println("You win");
}
else
{
System.out.println(head+" Heads");
System.out.println("You lose");
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
headtail ht=new headtail();
FileInputStream fi=new FileInputStream("head-tail.txt");
ht.coinFlip(fi);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.