【发布时间】: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 个猜测。
【问题讨论】: