【问题标题】:Creating High Low game and the count down prints down to 0 in one guess and ends the game. How do I correct this so it counts down for each guess?创建 High Low 游戏,一次猜中倒计时打印到 0 并结束游戏。我该如何纠正这个问题,以便每次猜测都会倒计时?
【发布时间】:2021-10-19 10:59:30
【问题描述】:

游戏要求用户输入可能的最低值和可能的最高值。然后计算机在给定值之间选择一个随机数。用户有一定数量的猜测取决于给定的范围。用户应该猜出这个数字,如果猜错了,程序应该告诉用户猜测是高还是低,并告诉用户还剩下多少猜测。问题是当您猜测时,计数器会在第一次猜测时倒数为零。请参阅下面的代码和结果。

import java.util.Scanner;

public class highlow {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.println("Lets play a game! Let me know a range, I will pick a number and 
        you guess what it is.");
        System.out.println("What is the lowest possible value? ");
        int min=sc.nextInt();
        System.out.println("What is the highest possible value? ");
        int max=sc.nextInt();
        System.out.println("Great I will think of a number between " + min + " and " + max);

        double y=Math.sqrt(max-min+1);  //Calculation for # of guesses
        double DoubleValue=y;
        int IntValue=(int) DoubleValue;     //turn double into integer 
        System.out.println("You have " + IntValue + " guesses left.");

        int correctNum=(int)Math.floor(Math.random()*(max-min+1)+min);

        int i;
        for(i=IntValue; i>=0; i--){
        System.out.println("What is your guess? ");
        int guess=sc.nextInt();
        while(i>0){
        if(guess < correctNum){
            System.out.println("number is too low! You have " + i-- + " guesses left.");
        }
        else if(guess > correctNum){
            System.out.println("Number is too high! You have " + i-- + " guesses left.");
        }
        else if(guess == correctNum){
            System.out.println("You Win! Are you smart or did you cheat?");
        }
        else{
            System.out.println("not a valid option");
        }
    }
    }
}
}

结果: 来玩个游戏!让我知道一个范围,我会选择一个数字,你猜它是什么。 可能的最低值是多少? 1 可能的最高值是多少? 50 太好了,我会想到一个 1 到 50 之间的数字 你还有 7 个猜测。 你的猜测是什么? 9 数量太少了!你还有 7 个猜测。 数量太少了!你还有 6 个猜测。 数量太少了!你还有 5 个猜测。 数量太少了!你还有 4 个猜测。 数量太少了!你还有 3 个猜测。 数量太少了!您还有 2 个猜测。 数量太少了!您还有 1 个猜测。

【问题讨论】:

    标签: java random counter


    【解决方案1】:

    为什么在打印语句中使用i--?这将减少变量i

    尝试改用(i-1),因为这不应该减少 i 的值。

    另外,我相信您不需要while(i&gt;0) 循环。 您已经在使用for(i=IntValue; i&gt;=0; i--) 循环猜测的次数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 2020-11-22
      相关资源
      最近更新 更多