-2

I'm asked to implement a program that generates a random number of jelly beans in a jar, prompt the user to make a guess on how many jelly beans are in the jar, and count how many times the user tried to guess before getting it right.

That's my problem right there -- getting the program to count how many times the user inputted a guess. Here's my code:

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





}

}

4

3 回答 3

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);
于 2013-09-25T19:41:04.697 回答
1

在该do部分之前,定义一个变量,int guessesCount = 0;然后在每个之后递增它scanguessesCount++;

于 2013-09-25T19:41:39.627 回答
0

这是微不足道的:

 int count = 0;

 // inside while loop
      count++;

 // outside while loop

 // do what you want with count
于 2013-09-25T19:41:51.707 回答