While I was writing this I had some thoughts and questions going through my head about if I was doing this in a good manner. For instance, is it good to use a StringTokenizer
to loop through the words in the line I copied from the Scanner's input?
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.
public static void coinFlip(Scanner input) {
int countHeads = 0;
int countTails = 0;
double count = 0.0;
double ratio = 0.0;
String line = "";
while(input.hasNextLine()) {
countHeads = 0;
countTails = 0;
line = input.nextLine();
StringTokenizer lineTokens = new StringTokenizer(line);
while (lineTokens.hasMoreTokens()) {
String token = lineTokens.nextToken();
if (token.toLowerCase().equals("h")) {
countHeads++;
} else {
countTails++;
}
}
count = countTails + countHeads;
ratio = Math.abs(1 - (countTails/count)) * 100;
System.out.printf(countHeads + " heads (%1.1f%%)\n", ratio);
if (countHeads > countTails) {
System.out.println("You win!\n");
}
else {
System.out.println();
}
}
}
String.split()
because its behaviour is tricky. \$\endgroup\$