I am writing a coin toss program. Basically, the user is asked how many games they want to play. Then, the while loop runs the game which asks the user to input a several coin tosses separated by spaces (heads or tails ex. H H H T H). Then the program converts the user input string into an array and the for loop goes through the array and checks for heads (capital H) and it is stored in the heads variable. The the score is calculated by diving the number of heads in the array by the length of the array and multiplies it by 100 to make a percentage. If the score is 50% or above, the player wins. If below 50%, the player loses. Two bugs I found were the while loop already runs once before i put in any input. Also the score seems to be calculated incorrectly where it either always returns 0.0% or 100.0%. I think it has something to do with the inputArray.length but I cannot tell. Thank you.
import java.util.Scanner;
public class HeadTailGenerator {
public static void main (String []args) {
Scanner scanner = new Scanner(System.in);
System.out.print("How many games?");
int games = scanner.nextInt();
int count = 0;
int heads =0;
while (count<games){
System.out.print("Enter your flips for game "+ count+": ");
String input = scanner.nextLine();
String [] inputArray = input.split("\\s+");
for (int i = 0; i <inputArray.length-1; i++){
if (inputArray[i].equals("H")){
heads++;
}
}//exit for loop
double score = (heads/(inputArray.length)*100);
if (score >= 50.0){
System.out.println("Game "+ count + ": "+ heads + " heads ("+ score+ "%); You win!");
}
else {
System.out.println("Game "+ count + ": "+ heads + " heads ("+ score+ "%); You lose!");
}
count++;
}
}
}