从函数到新函数获取随机int

时间:2014-11-10 03:24:56

标签: java function recursion random

我正在尝试用java做一个简单的猜谜游戏。我有创建随机数和猜测数字的功能。但是,在猜测数字时,没有变量被声明为随机猜测。我想知道如何从猜测函数中的一个函数中获取我的随机数。这是我的代码:

public static void Final(){
    Random rand = new Random();
    int number = rand.nextInt(10) + 1;
}

public static void Guess(){

    Scanner scan = new Scanner(System.in);
    int pick = scan.nextInt();

    if(pick > number){
        System.out.println("Your number is too high.");
        Guess();            
    }else if(pick < number){
        System.out.println("Your number is too low.");
        Guess();
    }else if(pick == number){
        System.out.println("Correct!");
    }

1 个答案:

答案 0 :(得分:1)

您应该更改getFinal()方法以返回int:

public static int getFinal(){
    Random rand = new Random();
    return rand.nextInt(10) + 1;
}

然后在您的makeGuess()方法中:

public static void makeGuess(){
    int number = getFinal(); //number to be guessed

    myLoop:
         while(true){ //loop until they get it right
              Scanner scan = new Scanner(System.in);
              int pick = scan.nextInt();
              if(pick > number){
                  System.out.println("Your number is too high.");            
              }else if(pick < number){
                  System.out.println("Your number is too low.");
              }else if(pick == number){
                  System.out.println("Correct!");
                  break myLoop;
              }
         }
}

另外,作为旁注,方法应该是camelCase,并且在其名称中包含动词。