簡體   English   中英

在子類java中使用對象

[英]Using objects in a subclass java

我想使用我在子類的一個類中聲明的對象,但它給了我無法從靜態上下文中引用的非靜態變量我是一個初學者,所以我可以改變什么來使這項工作

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++;
            }
        }

        }
    }
}

(忽略滾動方法它是其他東西的一部分)

如下圖移動你的骰子實例。 在同一個nextInt()調用中減 1 nextInt() 1 沒有意義。 由於您的代碼中還有其他有問題的結構,更好的問題可能是尋求幫助以實現最終目標。

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++;
            }
        }

        }
    }
}

您是否嘗試過將內部類設為靜態?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM