0

我编写的代码可以编译,但不会产生我期望的输出。它在我输入所有输入数据并且没有给我正确的输出之前结束。知道错误在哪里吗?

这是主程序:

public static void main(String[]args)
{
    Scanner keyboard = new Scanner(System.in);
    String coinFlip;
    int tossNumber, numberOfHeads, numberOfTails;
    float percHeads, percTails;
    tossNumber = 1;
    numberOfHeads = 0;
    numberOfTails = 0;

    while(tossNumber <= 8)
    {
        System.out.println("Please toss your coin and enter the side    showing.");
        System.out.println("h = heads, t = tails");
        coinFlip = keyboard.next();

        if(coinFlip.equals("h") || coinFlip.equals("t"))
        {
            if(coinFlip.equals("h"))
            {
                System.out.println("Thank you! Please toss your coin again.");
                tossNumber = tossNumber + 1;
                numberOfHeads = numberOfHeads + 1;
            }
            else

                System.out.println("Thank you! Please toss your coin again");
                tossNumber = tossNumber + 1;
                numberOfTails = numberOfTails + 1;

        }
        else
            System.out.println("Please enter a \"h\" or \"t\".");
    }
4

1 回答 1

3

我所做的只是添加{}到你的else,我得到了完美的 8 次,希望那是预期的。

import java.util.Scanner;

public class MC_GAMAD {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        String coinFlip;
        int tossNumber, numberOfHeads, numberOfTails;
        float percHeads, percTails;
        tossNumber = 1;
        numberOfHeads = 0;
        numberOfTails = 0;

        while (tossNumber <= 8) {
            System.out
                    .println("Please toss your coin and enter the side    showing.");
            System.out.println("h = heads, t = tails");
            coinFlip = keyboard.next();

            if (coinFlip.equals("h") || coinFlip.equals("t")) {
                if (coinFlip.equals("h")) {
                    System.out
                            .println("Thank you! Please toss your coin again.");
                    tossNumber = tossNumber + 1;
                    numberOfHeads = numberOfHeads + 1;
                } else {
                    System.out
                            .println("Thank you! Please toss your coin again");
                    tossNumber = tossNumber + 1;
                    numberOfTails = numberOfTails + 1;
                }

            } else {
                System.out.println("Please enter a \"h\" or \"t\".");
            }

        }

    }
}
于 2015-10-28T18:27:31.033 回答