Math.Random始终将随机数设置为0

时间:2019-05-31 11:00:47

标签: java math random

创建一个程序,其中使用math.random生成随机数,我将其放入函数中并在程序中调用此函数以使事情更整洁,但输出的随机数始终是整数secret_number设置为,我不确定如何解决此问题以创建一个随机数。我想在函数中保留math.random并使用参数

package guessinggame3;
import java.util.Scanner; //imports scanner to read from keyboard
import java.util.ArrayList;


public class GuessingGame3 { //start of public class

static Scanner kboard = new Scanner(System.in); //calls scanner 


public static void main(String args[]) //start of main 
{

System.out.println("Welcome to the guessing game, the computer will 
generate a random number that you have to guess, good luck!"); //opening 
message explaining how to play 

int secret_number = 0;
int number_of_guesses = 0;
int user_guess ;
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();


generate_random_number(secret_number); //calls he function 
generate_random_number to say the random number has been generated 




for(int i=0; i<20;i++) { // start of for loop sets user attempts to 20


System.out.println("Please make your guess"); //asks user to enter make 
their guess             
user_guess = kboard.nextInt();
number_of_guesses++; // adds on to the counter after each user guess


if(entered_numbers.contains(user_guess)) //checks if entered number = 
number stored in array
{
System.out.println("You have already entered this number"); //displays 
error message if user enters same number again
continue;
}

else 
{
entered_numbers.add(user_guess);
if (user_guess == secret_number)
System.out.println("Your guess is corret you win!");
}

if (user_guess < secret_number)
{
System.out.println("Guess is too low");
}

if (user_guess > secret_number) 
{
System.out.println("Your guess is too high");
}


System.out.println (20 - number_of_guesses + " Guesses remaining"); 
//Tells the user how many guesses they have remaining 


} //end of for loop

} //end of main

static void generate_random_number(int secret_number)  //start of function 
generate_random_number function passing secret_number as a parameter
{       
secret_number = (int)(Math.random()*100) + 1; //generates random number 
between 0 and 100
System.out.println("The computer has generated it's number"); //lets the 
user know that the random number has been generated
} //end of function generate_random_number

} //公共课程结束

2 个答案:

答案 0 :(得分:0)

secret_number传递给函数generate_random_number时,将复制secret_number。因此,当您在函数内将secret_number分配给(int)(Math.random()*100) + 1时,您只是在更改其副本。

答案 1 :(得分:-1)

您应该将方法的返回类型更改为int。 像这样更改您的方法:

static int generate_random_number(int secret_number) 

然后在主函数中将您的secret_number设置为方法返回的值

secret_number = generate_random_number(secret_number);

您还应该为您的方法添加返回值,因此应该像这样:

static int generate_random_number(int secret_number){       
    secret_number = (int)(Math.random()*100) + 1;
    System.out.println("The computer has generated it's number");
    return secret_number;
}