我知道此问题之前已经得到解答,我看过这里:math.random, only generating a 0? 以及其他几个论坛,但到目前为止一直无法回答我的问题。
我正在尝试为Rock Paper Scissors游戏生成1到3之间的随机数(包括1& 3)。不幸的是,我随机数的输出总是为0.
请注意,我不允许使用Random(); class,并且必须使用Math.random方法来实现这一点。这是我的随机数代码:
public static int randomComputerChoice(int highVal, int lowVal) {
do{
highVal = 4;
lowVal = 0;
computerChoice=0;//resets random number
//generates and returns a random number within user's range
computerChoice = (int)((Math.random()* highVal)+1);
} while((computerChoice>= highVal)||(computerChoice<= lowVal));
return (computerChoice);
}
}
我不确定这是否有必要,但我觉得错误可能出现在我的其余代码中。
import java.util.Scanner;
import java.io.IOException;
public class RockPaperScissors {
static int weaponChoice;
static int computerChoice;
static int lowVal = 1;
static int highVal = 3;
/**
* @param args the command line arguments
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException {
Scanner userInput = new Scanner(System.in);
System.out.println(" =========================");
System.out.println("====ROCK=PAPER=SCISSORS====");
System.out.println(" =========================");
int playAgain = 1; //sets a play again function
do {
System.out.println("Please select your weapon.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
System.out.println("Choose wisely:");
String choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
do {
if (weaponChoice != 1 && weaponChoice != 2 && weaponChoice != 3) {
System.out.println("Please choose again, grasshopper. There are only"
+ " three choices.");
System.out.println("1 - Rock");
System.out.println("2 - Paper");
System.out.println("3 - Scissors");
choice = userInput.nextLine();
weaponChoice = Integer.parseInt(choice);
}
} while (weaponChoice != 1 && weaponChoice !=2 && weaponChoice != 3);
if (weaponChoice == 1) {
System.out.println("You have selected Rock as your weapon.");
}
else if (weaponChoice == 2) {
System.out.println("You have selected Paper as your weapon.");
}
else {
System.out.println("You have selected Scissors as your weapon.");
}
//Computer's Choice
System.out.println("The computer's choice is "+computerChoice);
} while (playAgain == 1);
}
public static int randomComputerChoice(int highVal, int lowVal) {
do{
highVal = 4;
lowVal = 0;
computerChoice=0;//resets random number
//generates and returns a random number within user's range
computerChoice = (int)((Math.random()* highVal)+1);
} while((computerChoice>= highVal)||(computerChoice<= lowVal));
return (computerChoice);
}
}
感谢您的帮助!非常感谢。
答案 0 :(得分:0)
尝试:
Min + (int)(Math.random() * ((Max - Min) + 1))
。输出应该是1到3之间的数字。
填写1分钟,最多3分钟。就是这样。数字范围应该是:[1,3]这意味着包括1 AND 3.
这是另一个建议:
int number = 1 + (int)(Math.random() * ((3 - 1) + 1));
System.out.println(number);
//alternative way:
// return number;