第一次发表海报。如果这样做不正确,请善待。完全披露这是一个介绍java类,但我已经把这个项目改为我只是想重做它来修复我的错误
主要问题是了解对象和类的基础知识。该程序应该模拟Yahtzee 5骰子卷。我需要创建一个骰子类,然后创建5个骰子对象,在1到5之间滚动一个随机值。目前我创建了一个名为OneDice的类:
public class OneDice {
private int die; // variable for a dice
public OneDice() {
roll(); //constructor
}
public void roll() {// random
die = (int)(Math.random()*6) + 1;
}
public int value() {
// return the value of the die variable
return die;
}
接下来我们要创建一个Yahtzee类,其中“保存五个骰子对象”是我创建的:
public class Yahtzee {
private int dice1;
private int dice2;
private int dice3;
private int dice4;
private int dice5;
public Yahtzee(){
yahtzeeRoll(); //constructor
}
public void yahtzeeRoll(){
OneDice diceA = new OneDice();
OneDice diceB = new OneDice();
OneDice diceC = new OneDice();
OneDice diceD = new OneDice();
OneDice diceE = new OneDice();
dice1 = diceA.value();
dice2 = diceB.value();
dice3 = diceC.value();
dice4 = diceD.value();
dice5 = diceE.value();
}
public void printYahtzee(){ //prints the dices and graphics
System.out.println("dice 1 comes up= " + dice1);
System.out.println("dice 2 comes up= " + dice2);
System.out.println("dice 3 comes up= " + dice3);
System.out.println("Dice 4 comes up= " + dice4);
System.out.println("Dice 5 comes up= " + dice5);
}
现在我明白这是可怕的编码。使用dice1 = diceA.value
等行。如何创建可分配给每个骰子的OneDice对象的五个单独实例。我知道这是非常基本的东西。我曾尝试重读我的教科书和在线阅读内容,但却无法弄明白。提前致谢。我希望他的主题不是太广泛:(
完整说明:
创建一个模拟单个六面骰子的类。模具的值可以是1到6.构造函数应该将模具设置为随机值(即模具永远不应以零值开始)。它应该有两种方法。一个称为roll,随机将模具设置为新值。另一个称为值,返回骰子的当前值。
创建一个名为Yahtzee的第二个类,它包含五个骰子对象。有一个名为roll的方法可以滚动所有五个骰子。有一个名为show的方法,它显示五个骰子中每个骰子的值。
您的主要课程应滚动五个骰子,显示结果,然后询问用户是否要再次掷骰子。
答案 0 :(得分:1)
我会改写你的Yhatzee类来使用这样的数组(这假设你想要保持不同的骰子,我个人会这样,以后我可以回忆起特定骰子的值,但是如果这是不必要的话,你没有具体的理由这样做);
public class Yahtzee {
private Dice[] dice;
private final int DICE_COUNT=5;
public Yahtzee(){
dice=new Dice[DICE_COUNT];
for(int i =0;i<DICE_COUNT;i++)
dice[i] = new Dice();
yahtzeeRoll(); //constructor
}
public void yahtzeeRoll(){
for(int i =0;i<DICE_COUNT;i++)
dice[i].roll();
}
public void printYahtzee(){ //prints the dices and graphics
for(int i =0;i<DICE_COUNT;i++)
System.out.println("dice "+(i+1)+" comes up= " + dice[i].value());
}
}
答案 1 :(得分:1)
您可以创建ArrayList
或Array
来保存值,并使用for循环创建值,使用for循环来打印值,如下所示:
import java.util.ArrayList;
import java.util.List;
public class Yahtzee {
// Two options, either keep a list of dices, or a list of the value of
// dices, the first option is more sensible to me
// Option 1
private List<OneDice> dices;
public Yahtzee(int numberOfRolls) {
this.dices = new ArrayList<>();
yahtzeeRoll(numberOfRolls);
}
public void yahtzeeRoll(int numberOfRolls) {
for (int i = 0; i < numberOfRolls; i++) {
OneDice dice = new OneDice();
dices.add(dice);
}
}
public void printYahtzee() {
for (OneDice dice : dices) { // This is an enhanced for loop
System.out.println("Dice rolled: " + dice.value());
}
}
public static void main(String[] args) {
Yahtzee yahtzeeGame = new Yahtzee(5);
yahtzeeGame.printYahtzee();
}
}