[英]Guessing Game, loop error
I'm having a problem with the following code for a guessing game, range set for 1-32. 我的猜谜游戏的以下代码有问题,范围设置为1-32。 It starts up, but once I take my first guess, I'm given either Too High or Too Low,plus the correct answer. 它开始了,但是一旦我做出第一个猜测,我就会得到“太高”或“太低”的信息,再加上正确的答案。 So I'm always able to get the correct answer in 2 guesses, which isn't suppose to happen. 因此,我总是能够在2个猜测中获得正确答案,这是不可能发生的。 I think I have a problem with the while loop. 我认为while循环有问题。
import java.util.Scanner;
import java.util.Random;
public class GuessingGame1 {
public static void main(String[] args) {
/*
* Following should create a random number
* Generated by computer between 0-32
*/
Random rng = new Random ();
int value = rng.nextInt(32);
int numberOfTries = 0;
Scanner input = new Scanner (System.in);
int guess = 0;
boolean win = false;
while (win == false) {
System.out.println("Guess of a Number between 1-32, I will tell you \n " +
"if your guess is too high, too low, or correct!");
/*
* Uses makes a guess and program tells if the guess is correct,
* too high, or too low.
*/
System.out.println("Enter your guess: ");
guess = input.nextInt();
numberOfTries++;
if (guess == value){
win = true;
} else if (guess > value){
System.out.println("Your guess is too high, try again");
} else if (guess < value){
System.out.println("Your guess is too low, try again");
}
System.out.println("Yes, the number is " + value);
System.out.println("It took you " + numberOfTries + " tries");
}
}
}
Move 移动
System.out.println("Yes, the number is " + value);
System.out.println("It took you " + numberOfTries + " tries");
into your condition here: 在这里您的情况:
if (guess == value){
win = true;
}
Otherwise, it will be called unconditionally - meaning in every iteration of the loop. 否则,它将无条件调用-意味着在循环的每次迭代中。 Alternatively, you can print it after your while loop, as the game is finished there. 另外,您也可以在while循环后打印它,因为游戏在那里完成了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.