循环不像我期望的那样

时间:2015-10-28 18:14:34

标签: java while-loop off-by-one

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

这是主程序:

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\".");
    }

1 个答案:

答案 0 :(得分: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\".");
            }

        }

    }
}