【问题标题】:to.UpperCase skips the process where it should workto.UpperCase 跳过它应该工作的过程
【发布时间】:2017-10-13 02:04:46
【问题描述】:

我正在开发一个抛硬币程序,并希望允许用户使用 toUpperCase() 输入小写或大写的正面/反面。但是由于某种原因,在我输入正面或反面后,它会跳过整个循环过程并打印最后一条语句。我不知道为什么,因为我有类似的程序,它工作得很好。感谢您的建议!

    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++;

【问题讨论】:

  • 好吧,至少,您将其转换为大写并与小写进行比较。没有关于循环的任何线索,因为您没有包含所有循环,但请确保字符串正是您认为的那样。
  • 尝试打印变量或使用调试器来帮助您快速解决此类问题
  • 如果你写"HEADS" 代替"heads" 会发生什么?
  • @DaveNewton 你的意思是 predict = predict.toUpperCase()+predict.toLowerCase(); ?我也试过了,还是不能正常工作。还是有其他比较方法?
  • @DawoodibnKareem 它会跳过掷硬币的过程,直到我询问用户是否想玩或退出的最后打印。虽然它不会停止程序

标签: java loops uppercase


【解决方案1】:

使用equalsIgnoreCase 代替equals。然后你不必考虑大写/小写(顺便说一句,你搞混了)

【讨论】:

    猜你喜欢
    • 2014-10-05
    • 1970-01-01
    • 2020-11-03
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    相关资源
    最近更新 更多