第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

什么是非靜態(tài)變量以及如何修復(fù)它們

什么是非靜態(tài)變量以及如何修復(fù)它們

夢里花落0921 2023-07-19 17:09:25
我有一個家庭作業(yè),我應(yīng)該使用 math.random() 模擬擲骰子并將其更改為 int 。我有一個包含 2 個類的文件,并且正在嘗試創(chuàng)建一個對象。我的代碼編譯時出現(xiàn)運(yùn)行時錯誤“錯誤:無法從靜態(tài)上下文引用非靜態(tài)變量?!?nbsp;知道發(fā)生了什么。我已將“value”的值更改為整數(shù)并成功運(yùn)行代碼。目前還沒有想到其他改變。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;        }    }}期望控制臺打印出數(shù)字 1 <= x < 7 作為整數(shù)。錯誤信息:error: non-static variable this cannot be referenced from a static context        Die myDie = new Die();                    ^
查看完整描述

2 回答

?
RISEBY

TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超5個贊

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


class DieTester_5AlastiCorrigan {

    ...

}


class Die {

    ...

}

或者添加一個static修飾符:


class DieTester_5AlastiCorrigan {

    ...


    static class Die {

        ...

    }

}

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


public Die() {

    this(1);

}

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


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

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超6個贊

class Die 是類 DieTester_5AlastiCorrigan 的實(shí)例變量,這意味著您只能使用 DieTester_5AlastiCorrigan 實(shí)例創(chuàng)建 Die 實(shí)例。這段代碼應(yīng)該運(yùn)行:


DieTester_5AlastiCorrigan outerObject = new DieTester_5AlastiCorrigan();

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


查看完整回答
反對 回復(fù) 2023-07-19
  • 2 回答
  • 0 關(guān)注
  • 137 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號