这个程序假设是一个游戏,我向用户询问2个数字的低位和高位,它可以是任何顺序。生成器将在这两个数字之间创建一个随机数,并将继续向用户询问一个数字,直到他们得到答案。 我唯一的问题是提示用户是否想要玩游戏: 这是我现在的代码。
import java.util.*;
public class tester
{
public static void main(String [] args)
{
Scanner S = new Scanner(System.in); //Introduction Statement to game
System.out.println("This is a guessing game. I will ask you for two numbers.");
System.out.println("I will choose a random number between your two numbers for you " + "\n" + "to try and guess. As you guess, I will give you hints.");
System.out.print("Choose two numbers to bound your range: "); //Scanner to store user's input for the range
int u1 = S.nextInt();
int u2 = S.nextInt();
int guess;
int count = 0; // = 0 new
String playAgain = "Y";
int high;
int low;
if(u1 < u2)
{
high = u2;
low = u1;
}
else
{
high = u1;
low = u2;
}
Random gen = new Random();
int rand = gen.nextInt(high-low+1) + low;
System.out.println("Now guess a number between " + low + " and " + high + ": ");
guess = S.nextInt();
while (playAgain.equalsIgnoreCase("Y"))
{
System.out.println("Now guess a number between " + low + " and " + high + ": ");
guess = S.nextInt();
while(guess != rand)
{
count++;
if (guess > high || guess < low)
{
System.out.println("Out of range. Please follow the directions dumb-ass.");
}
else if(guess > rand)
{
high = guess;
System.out.println("Too high!");
}
else
{
low = guess;
System.out.println("Too low!");
}
System.out.print("Now guess a number between " + low + " and " + high + ": ");
guess = S.nextInt();
if(guess == rand)
{
System.out.println("you got it!.");
}
else if(count == 10)
{
System.out.println("You lost! So Sorry.");
//break;
}
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
S.nextLine();
playAgain = S.nextLine();
}
}
}
}
答案 0 :(得分:0)
使用2个嵌套循环而不是1个。
String playAgain = "Y";
while(playAgain.equalsIgnoreCase("Y"))
{
Scanner S = new Scanner(System.in);
//Introduction Statement to game
System.out.println("This is a guessing game. I will ask you for two numbers.");
System.out.println("I will choose a random number between your two numbers for you " + "\n" + "to try and guess. As you guess, I will give you hints.");
System.out.print("Choose two numbers to bound your range: "); //Scanner to store user's input for the range
int u1 = S.nextInt();
int u2 = S.nextInt();
int guess;
int count = 0; // = 0 new
int high;
int low;
int gameHasEnded = 0;
while(!gameHasEnded)
{
// do game stuff here; after he won or lost, set gameHasEnded = 1
}
System.out.println("Would you like to play again? Enter Y to play or any other key to quit: ");
S.nextLine();
playAgain = S.nextLine();
通过这种方式,您可以区分这两个事件(1)游戏已经结束(无论出于何种原因)和(2)再次播放它。
答案 1 :(得分:0)
你只需要在函数中放置代码。
执行新函数后,如果用户输入等于Y,则再次执行
否则你只需返回^^