亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

什么是非靜態變量以及如何修復它們

什么是非靜態變量以及如何修復它們

夢里花落0921 2023-07-19 17:09:25
我有一個家庭作業,我應該使用 math.random() 模擬擲骰子并將其更改為 int 。我有一個包含 2 個類的文件,并且正在嘗試創建一個對象。我的代碼編譯時出現運行時錯誤“錯誤:無法從靜態上下文引用非靜態變量?!?nbsp;知道發生了什么。我已將“value”的值更改為整數并成功運行代碼。目前還沒有想到其他改變。public class DieTester_5AlastiCorrigan {    public static void main(String[] args){        // New object myDie.         Die myDie = new Die();        System.out.println(myDie.roll());        System.out.println(myDie.getValue());    }    // Creates a new Die Class     class Die{        private String value;        public Die( int dieRoll ) {            value = "" + dieRoll;        }        // Roll Method chooses random number between 1 - 7 and makes it    an int.         public int roll() {            int max = 6;            int min = 1;            int range = max + 1;            int dieRoll = (int)Math.random()*range;            //dieRoll = (int)dieRoll;            return dieRoll;        }        // getValue Method returns final value of "value".         public String getValue() {            return value;        }    }}期望控制臺打印出數字 1 <= x < 7 作為整數。錯誤信息:error: non-static variable this cannot be referenced from a static context        Die myDie = new Die();                    ^
查看完整描述

2 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

Die請注意您的班級在班級內的情況DieTester_5AlastiCorrigan。這使得它成為一個非靜態內部類。您需要一個 的實例DieTester_5AlastiCorrigan來創建 的實例Die。因此,要解決此問題,只需移至Die頂層,如下所示:


class DieTester_5AlastiCorrigan {

    ...

}


class Die {

    ...

}

或者添加一個static修飾符:


class DieTester_5AlastiCorrigan {

    ...


    static class Die {

        ...

    }

}

但是,您的代碼中仍然存在一些錯誤。Die有一個接受 an 的構造函數int,但是當您創建Die,時Die myDie = new Die();,您沒有將 an 傳遞int給構造函數。我建議您添加一個無參數構造函數:


public Die() {

    this(1);

}

另外,value不應該是 類型String。它應該是一個int,并且從您的用法來看,roll應該更改 的值value而不是返回骰子卷。


查看完整回答
反對 回復 2023-07-19
?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

class Die 是類 DieTester_5AlastiCorrigan 的實例變量,這意味著您只能使用 DieTester_5AlastiCorrigan 實例創建 Die 實例。這段代碼應該運行:


DieTester_5AlastiCorrigan outerObject = new DieTester_5AlastiCorrigan();

DieTester_5AlastiCorrigan.Die myDie = outerObject.new Die();


查看完整回答
反對 回復 2023-07-19
  • 2 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號