繁体   English   中英

我的代码有什么问题?

[英]Whats wrong in my code?

我似乎无法跳过 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;
}

}

当您调用 randomNum() 时,您将获得另一个随机值。 尝试:

int expected = randomNum();
System.out.println(expected);
int guess = -1;
while(guess != expected) {
    ...
}
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!");
  }
}

这可能是你想要的。 如果是,请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM