Just been experimenting with a class in which 2 dice are thrown and the total calculated. I am using OOP setting the total to this.dice1+this.dice2. However, when instantiating a Dice in another class the dice1 & dice2 throw work fine and generate 2 random numbers between 1 and 6. However, the sumTotal just defaults to 0 rather than adding dice1 and dice2.
Dice class:
public class Dice {
//create a random class
Random random = new Random();
//constants set the boundaries of possible dice roll values
private final static int UPPER_DICE_ROLL_LIMIT=6;
private final static int LOWER_DICE_ROLL_LIMIT=1;
//instance vars
private int dice1;
private int dice2;
private int sumTotal;
/**
* default constructor
*/
public Dice() {
}
/**
* @param dice1
* @param dice2
* @param sumTotal
*/
public Dice(int dice1, int dice2) {
this.setDice1(dice1);
this.setDice2(dice2);
this.setSumTotal();
}
/**
* @return the dice1
*/
public int getDice1() {
return dice1;
}
/**
* sets the number of dice1's roll - must be >=1 & <=6
* @param dice1 the dice1 to set
*/
public void setDice1(int dice1) throws IllegalArgumentException {
if (dice1>=LOWER_DICE_ROLL_LIMIT && dice1<=UPPER_DICE_ROLL_LIMIT) {
this.dice1 = dice1;
}else {
throw new IllegalArgumentException("Invalid number");
}
}
/**
* @return the dice2
*/
public int getDice2() {
return dice2;
}
/**
* sets the number of dice2's roll - must be >=1 & <=6
* @param dice2 the dice2 to set
*/
public void setDice2(int dice2) throws IllegalArgumentException {
if (dice2>=LOWER_DICE_ROLL_LIMIT && dice2<=UPPER_DICE_ROLL_LIMIT) {
this.dice2 = dice2;
}else {
throw new IllegalArgumentException("Invalid number");
}this.dice2 = dice2;
}
/**
* @return the sumTotal
*/
public int getSumTotal() {
return sumTotal;
}
/**
* sets the total score of the two dice (dice1 + dice2)
* @param sumTotal the sumTotal to set
*/
public void setSumTotal() {
this.sumTotal = this.dice1 + this.dice2;
}
/**
* method to set randomly set the values of the dice rolls
*/
public void rollDice() {
this.setDice1(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
this.setDice2(random.nextInt(UPPER_DICE_ROLL_LIMIT)+1);
}
}
Game class:
public class Game {
public static void main(String[] args) {
Dice dice = new Dice();
dice.rollDice();
System.out.println(dice.getDice1());
System.out.println(dice.getDice2());
System.out.println(dice.getSumTotal());
}
}
Thanks in advance, Cameron
Aucun commentaire:
Enregistrer un commentaire