I want to use objects that I've declared in one class in a subclass but it gives me non-static variable cannot be referenced from static context I'm a beginner with this so what can I change to make this work
class PairofDice {
int d61;
int d62;
PairofDice d1 = new PairofDice();
PairofDice d2 = new PairofDice();
class BoxCars {
public static void main(String[] args) {
roll();
Random rand = new Random();
int BC = 0;
for (int i = 0; i < 1000; i ) {
d1.d61 = rand.nextInt(6 1 - 1) 1;
d2.d62 = rand.nextInt(6 1 - 1) 1;
if (d1.d61 d2.d62 == 12) {
BC ;
}
}
}
}
}
(ignore the roll method it's a part of something else)
CodePudding user response:
Here is a suggested structure for you code. They can be put in the same file with BoxCars (the goal of your program) to be declared public.
public class BoxCars {
public static void main(String[] args) {
PairOfDice dice = new PairOfDice();
int numberOfRolls = dice.roll();
System.out.printf("I rolled %d box cars%n", numberOfRolls);
}
}
class PairOfDice {
int d1;
int d2;
public int roll() {
// No need to create instances of dice here. Just use d1 and d2
// code here to count the dice that are box cars.
// you have already written this.
return BC;
}
}
CodePudding user response:
Have you tried making the inner class static?