我正在写一个java代码,要求用户猜测计算机的随机数,我很好,但是,我想要做的是有一个消息对应的猜测数拿走了用户。猜数字游戏java
例如,如果用户猜测1中的随机数,尝试输出“优秀!”。如果用户猜到2-4的答案尝试“好工作”等。
我想我还没有尝试过任何东西,因为我不知道在哪里粘住代码?
我知道它必须如果猜== = 1然后做这个如果代码> 1 < = 3然后这样做等等..但在我的代码?它应该在嵌套if的while循环中吗?
这是我更新的代码,它运行并编译我创建它所需的确切方式。感谢所有的帮助!
public static void main(String[] args) {
Random rand = new Random();
int compNum = rand.nextInt(100);
int count = 0;
Scanner keyboard = new Scanner(System.in);
int userGuess;
boolean win = false;
while (win == false){
System.out.print("Enter a guess between 1 and 100: ");
userGuess = keyboard.nextInt();
count++;
if(userGuess < 1 || userGuess > 100){
System.out.println("Your guess is out of range. Pick a number between 1 and 100.");
System.out.println();
}
else if (userGuess == compNum){
win = true;
System.out.println("Congratulations! Your answer was correct! ");
}
else if (userGuess < compNum){
System.out.println("Your guess was too low. Try again. ");
System.out.println();
}
else if (userGuess > compNum){
System.out.println("Your guess was too high. Try again. ");
System.out.println();
}
}
if(count == 1){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was lucky!");
}
else if (count > 1 && count <= 4){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was amazing!");
}
else if (count > 4 && count <= 6){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was good.");
}
else if (count > 6 && count <= 7){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was OK.");
}
else if (count > 7 && count <= 9){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("That was not very good.");
}
else if (count > 10){
System.out.println();
System.out.println("I had chosen " + compNum + " as the target number.");
System.out.println("You guessed it in " + count + " tries.");
System.out.println("This just isn't your game.");
}
}
}
你需要做的是向我们展示有问题的代码并解释你所尝试过的代码。你的问题有被关闭的危险,因为除了你的目标之外,你还没有提供任何相关的细节。首先决定如何将猜测次数映射到“奖励”短语,然后编写代码来实现该映射。 –
创建一个函数,它将获取的尝试次数作为参数,并返回一个包含所需消息的字符串。你需要使用某种控制结构来实现这一点,最简单的可能只是一堆if-else语句。至于这个问题,这里没有主题,因为很难真正给你一个简洁的答案,包括你试图解决问题的一些代码会很好。 – shuttle87
对不起,就像我在这里说的很新,看到了一些关于代码的帖子,但它与我的问题没有关系。我想我需要帮助的是如何将它嵌入我的代码中,是否应该将它放在一个大的嵌套循环中?对不起,我试图找出如何添加我的代码,以显示我有什么.. –