Search code examples
javaloopsuppercase

to.UpperCase skips the process where it should work


I am working on a coin toss program and wanted to allow a user to input either lower case or upper case heads/tails with toUpperCase(). But for some reason, after I input either way heads or tails it would skip the whole process of the loop and prints last statement. I am not sure why, because I had similar program and it worked just fine. Appreciate your suggestions!

    do {
        System.out.printf("Do you predict heads or tails for the coin toss?(heads or tails): ");
        String predict = in.next();
        System.out.print("Tossing a coin...");
        System.out.println();

        predict = predict.toUpperCase();

        int cointoss= (int) (Math.random()*OUTCOMES);
        if(predict.equals("heads") && cointoss==0){
            System.out.print("The coin came up heads. You win!");
            System.out.println();
            wins ++;

}

        System.out.print("Type \"c\" to continue or any other letter to quit: ");
        playAgain = in.next();
        if (playAgain.equals("c")){
            done = false;
        } else done = true;
        count++;

Solution

  • Use equalsIgnoreCase instead of equals. Then you don't have to think about upper/lower case (that you've mixed up, btw)