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)
Move your dice instances below as shown. And subtracting 1 and adding 1 in the same nextInt()
call doesn't make sense. As there are other questionable constructs in your code, a better question might have been to ask for help in achieving the end goal.
public class PairofDice {
int d61;
int d62;
class BoxCars {
public static void main(String[] args) {
// roll();
Random rand = new Random();
PairofDice d1 = new PairofDice();
PairofDice d2 = new PairofDice();
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++;
}
}
}
}
}
您是否尝试过将内部类设为静态?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.