果冻豆在猜测时循环?

时间:2013-09-25 19:38:27

标签: java

我被要求实施一个程序,在jar中生成随机数量的果冻豆,提示用户猜测罐中有多少果冻豆,并计算用户试图猜测的次数在做对了之前。

这就是我的问题 - 让程序计算用户输入猜测的次数。这是我的代码:

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);





}

}

3 个答案:

答案 0 :(得分:2)

有一个计数器变量,你在while循环中的每个循环上递增。像这样:

int num_guesses = 0;
do {
System.out.print("Enter your guess: ");//prompt user to quess and read in 
guess = scan.nextInt();
num_guesses++; // increment the number of guesses

    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
        System.out.println("It took you " + num_guesses + " guesses!"); // display message with number of guesses
    }
}   while (guess != numOfJellyBeans);

答案 1 :(得分:0)

do部分之前,定义一个变量int guessesCount = 0;,然后在每个scan之后将其递增:guessesCount++;

答案 2 :(得分:0)

这很简单:

 int count = 0;

 // inside while loop
      count++;

 // outside while loop

 // do what you want with count