-1

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)

1 Answers1

-1

Your question implies a nested class, and not what one would consider a subclass. Here is a suggested structure for your code. Before creating an instance of the inner class you need to have one of the containing class which in this case is BoxCars. You can rename the classes to whatever fits your requirement.

public class BoxCars {
       
    public static void main(String[] args) {
        BoxCars bc = new BoxCars();
        PairOfDice dice = bc.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() {
            int BC = 0;
            // 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;
        }
    }
}
WJS
  • 30,162
  • 4
  • 20
  • 36
  • right so this is for a class and i have to declare two dice objects in one class then in the BoxCars class i must use the objects to roll two d6s 1000 times and count the number of Box Cars( two 6s) . Also the new code still gives me the same error – LazersFixAll Nov 13 '21 at 22:34
  • I modifed my answer to offer some suggestions now that I understand the goal. It is up to you to add the code to the method (which you have already written). You can, of course, rename things. Like change `roll()` to `countBoxCars()`. – WJS Nov 13 '21 at 23:06