The question I am trying to solve is from the book Building Java Programs and is formatted as follows:
Write a method called coinFlip that accepts a Scanner representing an input file of coin flips that are head (H) or tail (T). Consider each line to be a separate set of coin flips and output the number and percentage of heads in that line. If it is more than 50%, print "You Win!".
Consider the following file:
H T H H T
T t t T h H
For the input above, your method should produce the following output:
3 heads (60.0%)
You Win!
2 heads (33.3%)
When I run the code it only outputs: "0 heads (0.0)". So i'm assuming it never enters the second while loop for some reason or I am using the "next" methods wrong.
import java.io.*;
import java.util.*;
public class CoinFlip {
public static void main(String[] args) throws FileNotFoundException{
Scanner input = new Scanner("Series1.txt");
PrintStream output = new PrintStream("Output.txt");
coinFlip(input, output);
}
public static void coinFlip(Scanner input, PrintStream output) {
while(input.hasNextLine()) {
Scanner linesc = new Scanner(input.nextLine());
int headCount = 0;
int totalNums = 0;
while(linesc.hasNext()) {
String letter = linesc.next();
if(letter.equalsIgnoreCase("H")) {
headCount++;
}
totalNums++;
}
double percent = findPercentage(headCount, totalNums);
output.println(headCount + " heads " + "(" + percent +")");
if(percent > 50.00) {
output.println("You win!");
}
}
}
public static double findPercentage(int num1, int num2 ) {
double percentage = (double)num1/num2 * 100;
return percentage;
}
}