我正在尝试创建一个猜谜游戏程序。用户输入一个数字并被告知该数字是否太高或太低,然后被告知再次猜测。我做了一个无限循环,我不知道如何改变它。我意识到如果猜错了,那么程序将继续检查错误的值并打印“错误的数字”消息。
package guessinggame;
import java.util.Scanner;
/**
*
* @author
*/
public class GuessingGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
int guesses; //number of users guesses
int housePick; //number the user must guess
int guess; //users guess
housePick = (int)((Math.random() * 100) +1 );
//sets housePick to random number from 1 to 100
System.out.println("I'm thinking of a number between 1 and 100") ;
//print "Im thinking of a nubmer between 1 and 100"
System.out.println("Can you guess what it is?");
//print "can you guess what it is"
System.out.println
("Enter a number from 1 to 100 (including 1 and 100)");
//prompt user to enter number
guess = input.nextInt();
//save entered number as guess
while (guess != housePick) //while guess doesnt = housePick...
{
if (guess > housePick) //and if guess > housePick...
{
if ((guess - 10) <= housePick )
//and if guess is 10 numbers away from housePick...
{
System.out.println("Close, but too high. Try again.");
//print "close but too high, try again"
}
else //if guess is not close and guess>housePick...
{
System.out.println ("Too high, try again.");
//then print "Too high, Try again"
}
}
else //If guess<housePick
{
if ((guess + 10) >= housePick) //AND if guess is close to housePick
{
System.out.println ("close, but too low.") ;
//then print "close, but too low"
}
else//If guess isnt close to housePick and is less than housePick...
{
System.out.println ("Too low.");//then print "too low"
}
}
}
System.out.println ("You win! It took you " + "guesses.");
//If guess = housePick print "Yout win! It took you (# of guesses)"
}
}