【发布时间】:2014-11-30 15:11:34
【问题描述】:
我知道这个问题之前已经回答过,我看过这里:math.random, only generating a 0? 以及其他一些论坛,但到目前为止一直无法回答我的问题。
我正在尝试为石头剪刀布游戏生成 1 到 3 之间的随机数(包括 1 和 3)。不幸的是,我的随机数的输出总是 0。
请注意,我不允许使用 Random();类,并且必须使用 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);
}
}
感谢您的帮助!非常感谢。
【问题讨论】:
-
忽略调用者提供的
highVal和lowVal的值并将它们替换为 4 和 0 的函数非常粗鲁。(为什么你有这些名称的静态成员? )