2013-04-06 75 views
0

我是新來的java,我很接近answers.i希望我可以有一些提示,但不是完整的答案。我寧願將自己的邏輯推出。while循環中的隨機數

/* 
Write a method named makeGuesses that will guess numbers 
between 1 and 50 inclusive until it makes a guess of at least 48. 
It should report each guess and at the end should report 
the total number of guesses made. Below is a sample execution: 
*/ 

guess = 43 
guess = 47 
guess = 45 
guess = 27 
guess = 49 
total guesses = 5 

public void makeGuesses(){ 
    Scanner sc=new Scanner(System.in); 
    Random rnd=new Random(); 
    int i=1 
    int counter=0; 

    while(i>=1 && i<=50){ 

     i=rnd.nextInt(); 
     System.out.println("guess = " + i); 
     counter++; 


    } 
    System.out.print("total guesses = "+ counter); 
} 

這有什麼錯我的代碼?我意識到雖然我解決我的我是1到50之間,但仍超過。

+0

這將打印出0-50個隨機數。像'guess = 10,guess = 50,guess = 73'。那是你要的嗎?最後它會打印出循環的數量。 – christopher 2013-04-06 11:34:27

+0

ya.That就是我想要的。但我得到的猜測= 1497208734.我認爲我在while循環中修復了它? – user2179615 2013-04-06 11:36:04

+2

已嘗試rnd.nextInt(50)?這會限制隨機數的範圍 – diogod 2013-04-06 11:36:08

回答

2

您必須指定在你的情況你rnd.nextInt();綁定我猜

rnd.nextInt(50) + 1; // (1 - 50) 

和審查你的情況,否則你的程序將永遠不會停止

while(i>=1 && i<=50) 

看一看文檔:

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

以下是java.util.Random.nextInt()方法的聲明。

public int nextInt(int n) 

參數 N - 這是對隨機數勢必要返回。必須是積極的。

返回值 該方法調用返回一個僞隨機數,在0(含)和n(不含)之間均勻分佈的int值。

+0

它的工作。但有些奇怪。當我輸入我的數字,最後一行不斷給我猜= 0。 – user2179615 2013-04-06 11:38:27

+0

由於他想排除0,它應該是'rnd.nextInt(50)+ 1'。 – 2013-04-06 11:43:04

+0

@user看看這段代碼'while(i> = 1 && i <= 50)'並找出錯誤。你什麼時候想讓程序停止猜測? – 2013-04-06 11:49:53