Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a method in Java named coinFlip that accepts as its parameter a Scanner fo

ID: 3556411 • Letter: W

Question

Write a method in Java 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.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class Ideone{
public static void coinFlip(Scanner sc){
String coinSet;
String[] coins;
int numHeads;
int total;
int i;
while(sc.hasNext()){
coinSet = sc.nextLine();
coins = coinSet.split(" ");
numHeads = 0;
total = 0;
for(i=0;i<coins.length;i++){
if(coins[i].length() > 0){
if(coins[i].charAt(0) == 'h' || coins[i].charAt(0) == 'H') numHeads++;
total++;
}
}
System.out.printf("%d heads (%.1f) ", numHeads, (double)numHeads*100/total);
if((double)numHeads*100/total > 50) System.out.println("You win!");
System.out.println();
}
}
  
public static void main(String args[]) throws FileNotFoundException{
FileReader file = new FileReader("data.txt");
Scanner sc = new Scanner(file);
coinFlip(sc);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote