我被要求实现一个程序,该程序可以在一个jar中生成一个随机数量的果冻豆,提示用户猜测jar中有多少个果冻豆,并且计算用户以前尝试猜测的次数做对了。果冻豆猜测while循环?
这就是我的问题 - 让程序计算用户输入猜测的次数。这里是我的代码:
import java.util.Scanner;
import java.util.Random;
public class JellyBeanGame
{
public static void main(String[] args)
{
int numOfJellyBeans = 0; //Number of jellybeans in jar
int guess = 0; //The user's guess
Random generator = new Random();
Scanner scan = new Scanner (System.in);
//randomly generate the number of jellybeans in jar
numOfJellyBeans = generator.nextInt(999)+1;
System.out.println("There are between 1 and 1000 jellybeans in the jar,");
do
{
System.out.print("Enter your guess: ");//prompt user to quess and read in
guess = scan.nextInt();
if(guess < numOfJellyBeans) //if the quess is wrong display message
{
System.out.println("Too low.");
}
else if(guess > numOfJellyBeans);
{
System.out.println("Too High.");
}
else
{
System.out.println("You got it"); // display message saying guess is correct
}
} while (guess != numOfJellyBeans);
}
}
你只是想跟踪的猜测数量?只需保留一个变量,并在scan.nextInt()返回时增加它。 –
@gamernb是的,我可以给你一个例子吗? –
同意gamemb:添加一个像int guessCount = 0这样的变量。在循环中,比如在猜测之后说,有一个guessCount ++。然后,您可以将您的显示信息更改为“您已获得”+ guessCount +“猜测”。 – rajah9