2013-09-25 127 views
-2

我被要求实现一个程序,该程序可以在一个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); 





} 

}

+1

你只是想跟踪的猜测数量?只需保留一个变量,并在scan.nextInt()返回时增加它。 –

+0

@gamernb是的,我可以给你一个例子吗? –

+0

同意gamemb:添加一个像int guessCount = 0这样的变量。在循环中,比如在猜测之后说,有一个guessCount ++。然后,您可以将您的显示信息更改为“您已获得”+ guessCount +“猜测”。 – rajah9

回答

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

你是说如果他们在第一次尝试时得到它,你就会写下“你花了0次猜测!”?只需在guess = scan.nextInt() –

+0

@gamernb后立即增加var,我不认为有人会那么幸运,但你是对的。 – fvrghl

+0

@fvrghl我想我现在明白了!感谢大家的帮助! –

0

do部分之前,定义一个变量int guessesCount = 0;然后就加一后各scanguessesCount++;

0

这是微不足道的:

int count = 0; 

// inside while loop 
     count++; 

// outside while loop 

// do what you want with count 
+0

因为返回计数对于void函数是错误的。 – dognose

+0

即使你做了 - 你的答案有一个3岁的孩子可以给的质量。 +代表是重要的,对吧? – dognose

+0

肯定是杰夫。这不像他试图解决P = NP。这是最简单形式的正确答案。为什么复杂的事情? –