[英]Random in Java, repeating same number
我的代碼:
public class SkillsDemoTwoCrapsGameClass {
public static void main(String[] args) {
RandomNumber diceRoll = new RandomNumber(); //Create instance diceRoll of class RandomNumber
play playGame = new play(); //Create instance playGame of class play
//Initialise variables from play class
playGame.diceRoll = diceRoll.randNum;
playGame.point = playGame.diceRoll;
playGame.newPoint = diceRoll.randNum;
System.out.println("WELCOME TO A GAME OF CRAPS!");
if(playGame.diceRoll == 7 || playGame.diceRoll == 11){
//Show the users point
System.out.println("Point: " + playGame.point);
System.out.println("------------------------------");
//Tell user they won
System.out.println("Congratulations you won, with a " + playGame.diceRoll);
}
else if(playGame.diceRoll == 2 || playGame.diceRoll == 3|| playGame.diceRoll == 12){
//Show the users point
System.out.println("Point: " + playGame.point);
System.out.println("------------------------------");
//Tell the user they lost
System.out.println("Sorry you lost, with a " + playGame.diceRoll);
}
else{
System.out.println("Point: " + playGame.point);
System.out.println("------------------------------");
while(playGame.point != playGame.newPoint || playGame.point == playGame.newPoint){
/*
BUG: (2/2/19)
User will receive their original roll again, causing them to always win
*/
//Roll dice again for the new point
playGame.newPoint = diceRoll.randNum;
//Checks if the user can win
if(playGame.point == playGame.newPoint){
System.out.println("Your new roll: " + playGame.newPoint + "\t\t Win");
break;
}
//Checks if the user has lost
else if(playGame.newPoint == 7){
System.out.println("Your new roll: " + playGame.newPoint + "\t\t Lose");
break;
}
//Check if user needs to roll again
else{
System.out.println("Your new roll: " + playGame.newPoint + "\t\t No help");
}
}
}
}
}
class RandomNumber{
Random rand = new Random();
int randNum = rand.nextInt(12) + 1;
}
class play{
int diceRoll, point, newPoint;
}
上面的代碼是針對擲骰子游戲的,我的問題是用戶何時需要獲得新點數。 他們沒有分配新的隨機數,而是收到與以前相同的數字。 有沒有辦法調用 RandomNumber 類,並獲得一個新的隨機數來分配給newPoint
變量?
謝謝
在RandomNumber
類中添加一個方法來生成一個新的 Roll。
class RandomNumber{
Random rand = new Random();
int randNum = rand.nextInt(12) + 1;
void Roll(){
randNum = rand.nextInt(12) + 1;
}
}
然后在下一步之前添加對Roll()
的調用。
//Roll dice again for the new point
diceRoll.Roll();
playGame.newPoint = diceRoll.randNum;
附加這一行
`RandomNumber diceRoll = new RandomNumber();`
就在之前
`playGame.newPoint = diceRoll.randNum;`
因為您始終使用相同的對象和相同的 randNum 屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.