2016-05-30 23 views
-4

我似乎不能跳過while循環,因爲我的代碼不明白我輸入了正確的數字。我的代碼有什麼問題?

import java.util.Scanner; 
public class HelloWorld1{ 
    static Scanner userInput = new Scanner(System.in); 
     static int randomNumbe 

public static void main(String[] args){ 
    System.out.println(randomNum()); 
    int randomGuess = -1 ; 
    while(randomGuess != randomNum()){ 
     System.out.println("Guess a number between 0 to 100"); 
     randomGuess = userInput.nextInt(); 
    } 
    System.out.println("Yes the random number is:" + randomGuess); 
} 

public static int randomNum(){ 
    randomNumber = (int) (Math.random()*101); 
    return randomNumber; 
} 

}

+1

你不打印任何地方的號碼。你在使用調試器嗎?因爲如果你能猜出一個沒有任何線索的隨機數,我認爲你有更好的職業追隨......換句話說:隨機數在每次迭代中都在變化。你怎麼知道這是對的? – Arc676

回答

0

當你調用randomNum(),你得到另一個隨機值回。嘗試:

int expected = randomNum(); 
System.out.println(expected); 
int guess = -1; 
while(guess != expected) { 
    ... 
} 
-1
package randomguess; 

import java.util.Scanner; 

public class RandomGuess { 

/** 
* @param args the command line arguments 
*/ 

static int randomNumber = 0; 

public static int getRandomInt() { 
    randomNumber = (int) (Math.random()*101); 
    return randomNumber; 
} 

public static void main(String[] args) { 

    Scanner sc = new Scanner(System.in); 

    int guessInt = sc.nextInt(); 
    int randomInt = getRandomInt(); 

    while(guessInt != randomInt) { 
     System.out.println("Better luck nextTime :D Random number was "+randomInt); 
     guessInt = sc.nextInt(); 
     randomInt = getRandomInt(); 
    } 
    System.out.println("Yeah! You are oracle!"); 
    } 
} 

這可能是你想要的東西。讓我知道如果是。

+0

爲什麼這應該是他想要的? OP的一些解釋應該是很好的。 – Tom

+0

@Tom我以爲他在尋求解決方案。這裏是。他可以比較代碼並找出錯誤的位置。 –