Reputation: 992
I am tasked with creating a fairly simple dice based board game using Java. I have initialized all the dice objects in the constructor, however when I try to a method from the dice class inside the game class, I get the error (object name) cannot be resolved. Forgive me if that explanation isn't clear but hopefully the code will make more sense. The error is encountered in the rollDice() method of the qwixx class.
public class qwixx {
public qwixx() {
dice white1 = new dice();
dice white2 = new dice();
dice red = new dice();
dice yellow = new dice();
dice green = new dice();
dice blue = new dice();
}
public void rollDice() {
white1.rollDice();
white2.rollDice();
red.rollDice();
yellow.rollDice();
green.rollDice();
blue.rollDice();
}
}
public class dice {
String colour;
int currentSide;
public dice() {
colour = "white";
rollDice();
}
public int rollDice() {
currentSide = (int)(Math.random() * 6 + 1);
return currentSide;
}
}
Upvotes: 0
Views: 65
Reputation: 23174
All your variables in the constructor must be declared at the class level.
public class qwixx {
// declare the dice variables at the class level (as 'fields')
dice white1;
// same for other dice : declare them here
public qwixx() {
// in the constructor you actually create the object and assign references to the class variables
white1 = new dice();
// idem for others
}
}
That's how all the methods in the class can have access to these fields.
Otherwise, your dice references would only be visible in the method where they were declared, in the constructor, and of course that's not what you want, and the cause of your errors.
Upvotes: 1