我被要求實現一個程序,該程序可以在一個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