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

s printDuplicates Main Page Problems Solve a Problem Show Header O BJP3 Exercise

ID: 3904564 • Letter: S

Question

s printDuplicates Main Page Problems Solve a Problem Show Header O BJP3 Exercise 6.15: coinFlip processing Scanner Whitaker Brand (on 2013/04/01) Favorite Language/Type: Author: Java file 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 HTH H T 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 Type your solution here 2 4

Explanation / Answer

First make one Text file named: InFile.txt and add some input lines in the file . Then use that file in the following JAVA program. The program has been compiled and executed succesfully. It works as intended in question.

-------------------------------------------------------------------------------------------------------------------------------------------------

import java.io.*;

import java.util.*;

public class FileInput {

public static void main(String[] args) throws FileNotFoundException{

Scanner in = new Scanner(new File("InFile.txt"));

coinFlip(in);

}

public static void coinFlip(Scanner in) {

while (in.hasNextLine()) {

int head = 0;

int tail = 0;

StringTokenizer tokens = new StringTokenizer(in.nextLine().toLowerCase());

while (tokens.hasMoreTokens()) {

String tok = tokens.nextToken();

if ("h".equals(tok)) {

head= head+1;

} else if ("t".equals(tok)) {

tail=tail+1;

}

}

double ratio = (( head *100.0)/ (head + tail));

System.out.printf("%d head (%1.1f%%) ", head, ratio);

if(head>tail)

System.out.println("You win! " );

else

System.out.println(" ");

}

}

}