gpt4 book ai didi

java - java中两个骰子的总和

转载 作者:行者123 更新时间:2023-12-01 23:41:07 25 4
gpt4 key购买 nike

所以我有一个掷骰子程序,到目前为止似乎可以工作,但我无法弄清楚的唯一问题是如何对掷骰子的输出求和。它会再次掷骰子,同时对前一次掷骰子进行求和。

这是我开始的 Die 类

public class Die{   //only thing changed was removing implementation of the interface

private int noFaces;

public Die() {
noFaces = 6;
}

public int getNoFaces() { //getter
return noFaces;
}

public Die(int noFaces) { //setter, sets new value according to passed parameter
this.noFaces = noFaces;
}

public int roll() { //generates random number+1 within specified "noFaces" range
return (int) (Math.random() * noFaces + 1);
}

public void printRoll() { //goes to above method roll() and prints the returned value
System.out.println(roll());
}

}

并将一个骰子变成一对骰子,这就是我遇到求和问题的地方

public class PairOfDice {

private Die d1, d2;

public PairOfDice() { //initializes 2 die objects
d1 = new Die();
d2 = new Die();
}

public PairOfDice(int noFaces) { //sets the dice equally
d1 = new Die(noFaces);
d2 = new Die(noFaces);
}

public PairOfDice(int noFaces1, int noFaces2) { //sets dice separately
d1 = new Die(noFaces1);
d2 = new Die(noFaces2);
}

public void printRoll() { //prints rolls
System.out.println("Die 1 returned: " + d1.roll());
System.out.println("Die 2 returned: " + d2.roll());

}

public void printRollSum(){ //print sum of both rolls
System.out.println("Sum of both dice rolls are: " + (d1.roll() + d2.roll()));
}

}

以及我获得输出的地方,RollingDice

public class RollingDice {

public static void main(String[] args) {

PairOfDice pairOne = new PairOfDice();
pairOne.printRollSum();
System.out.println();

PairOfDice pairTwo = new PairOfDice(10);
pairTwo.printRoll();
pairTwo.printRollSum();
System.out.println();

PairOfDice pairThree = new PairOfDice(100, 3);
pairThree.printRoll();
pairThree.printRollSum();

}

}

感谢对我的程序或评论的所有帮助,我仍在学习。谢谢!

最佳答案

您得到的是两个骰子的总和,但您每次都在掷骰子。 printRoll() 滚动并显示值,然后 printRollSum() 再次滚动它们,为您提供不同的值。

关于java - java中两个骰子的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17951907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com