나는이 질문에 대한 답변을 이미 알고 있으며, 여기를 보았다 : math.random, only generating a 0? 뿐만 아니라 몇 가지 다른 포럼이지만, 지금까지 내 질문에 대답 할 수 없었다.Java Math.random이 0을 반환합니까?
나는 Rock Paper Scissors 게임을 위해 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으로 대체하는 함수의 매우 무례 (그리고 왜 당신이 할 그 이름을 가진 정적 멤버입니까?) – molbdnilo