如何编写Do / While验证?

问题描述 投票:5回答:1

我目前正在介绍Java类,我真的想改进,但我很难完成这项任务。任务的要求是

  1. 实现一个循环,允许用户通过键入yes继续玩游戏。
  2. 跟踪用户:胜利,损失和游戏使用递增变量播放
  3. 当用户不再希望继续时,打印显示跟踪变量的结果:Wins,Loss和Games Played
  4. 实现输入验证循环以确保用户输入正确的输入(h,t,H,T)

我相信我已经完成了除了最后一次之外的所有操作,我已经多次尝试使用do和while循环,但是我得到的最接近的是错误的输入循环,而正确的输入将绕过所有其他if / while / else语句。如果可能的话,我非常感谢有人看看我的代码并解释我可以做得更好,以及如何完成或接近最后的要求。

谢谢!

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String input, inputUpper;
    char userGuess;
    char coinFlip;
    int randNum;
    int wins = 0;
    int losses = 0;
    int total = 0;
    String choice = "yes";

    do {
        System.out.print("I will flip a coin guess 'H' for heads or 'T' for 
        tails --> ");
        input = scan.nextLine();

        inputUpper = input.toUpperCase();

        userGuess = inputUpper.charAt(0);
        randNum = (int) (Math.random() * 2);

        if(randNum == 0)
        {
            coinFlip = 'H';
        }
        else
        {
            coinFlip = 'T';
        }

        System.out.println("\nYou picked " + userGuess + 
        " and the coin flip was " + coinFlip + " so ...");

        if(userGuess == coinFlip)
        {
            System.out.println("You win!");
            wins ++;
            total ++;
        }
        else
        {
            System.out.println("Better luck next time ...");
            losses ++;
            total ++;
        }
        System.out.println("Do you want to continue(yes/no)?");
        choice=scan.nextLine();
    } while(choice.equalsIgnoreCase("yes"));
    System.out.println("Thank you for playing.");
    System.out.println("You guessed correctly this many times: " +wins);
    System.out.println("You guessed incorrectly this many times: " +losses);
    System.out.println("During this session you've played this many games: " +total);
    }
}

我希望程序要求T / t或H / h才能继续,如果用户输入错误的字母或数字,它会要求他们输入t或h。

java
1个回答
10
投票

这是验证输入的简单方法:

do {
    System.out.print("I will flip a coin guess 'H' for heads or 'T' for tails --> ");
    input = scan.nextLine();
    inputUpper = input.toUpperCase();
} while (!inputUpper.equals("T") && !inputUpper.equals("F"));

你可以在最后为“是”/“否”做同样的事情。

我觉得你做得很好。

© www.soinside.com 2019 - 2024. All rights reserved.