4 回答
TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
當(dāng)你定義
private void continueRound1 (ActionEvent event){
ROCK round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
您ROCK round1Rock只是為函數(shù)定義continueRound1。要Attack訪問該對(duì)象,您需要round1Rock在類級(jí)別上進(jìn)行定義。
嘗試:
ROCK round1Rock = null;
private void continueRound1 (ActionEvent event){
round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.hp = 12;
}
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
在類級(jí)別定義round1Rock,
class someclass
{
private ROCK round1Rock;
-----
private void continueRound1 (ActionEvent event){
round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.hp = 12;
}
------
}
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
而不是在 continueRound1 方法中創(chuàng)建一個(gè)新的 Rock 對(duì)象。您可以在類范圍內(nèi)創(chuàng)建新的 Rock 對(duì)象并設(shè)置私有訪問。這將解決您的問題。
附加提示:每次單擊按鈕時(shí),您都會(huì)創(chuàng)建一個(gè)新對(duì)象。如果我編寫程序無限期地單擊按鈕,這將導(dǎo)致OutOfMemoryError 。
以下是我避免此問題的見解:
我假設(shè)每個(gè)客戶都需要新的搖滾樂。因此,在客戶端類中創(chuàng)建一個(gè) Empty Rock 對(duì)象。
在您的客戶端構(gòu)造函數(shù)中,您可以使用巖石類型的默認(rèn)值初始化巖石對(duì)象。getDefaultRockForType 將幫助您創(chuàng)建任意數(shù)量的巖石類型。因此,我們將客戶端類中帶有一些值的 Rock 對(duì)象的實(shí)現(xiàn)細(xì)節(jié)隱藏為 Rock 類中的標(biāo)準(zhǔn)化值。
這是我的代碼片段:
Class Client {
private Rock round1Rock = new Rock();
Client() {
round1Rock = round1Rock.getDefaultRockForType("Metamorphic");
}
private void continueRound1 (ActionEvent event){
round1Rock= round1Rock.getDefaultRockForType("Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.setHp(12);
}
}
在您的 Rock 類中,您可以提供由您的巖石類型決定的默認(rèn)值。
類搖滾:
public Rock getDefaultRockForType(String type){
if(type.equals("Metamorphic")){
this.hp=500;
this.stamina= 100;
this.attack= 100;
this.speed = 100;
this.type = type;
}
}
TA貢獻(xiàn)1790條經(jīng)驗(yàn) 獲得超9個(gè)贊
首先像這樣聲明 ROCK 的實(shí)例是全局的
private ROCK round1Rock = null;
private void continueRound1 (ActionEvent event){
round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
private void Attack (ActionEvent event){
round1Rock.hp = 12;
}
在您的 Attack 動(dòng)作偵聽器中,您可能無法訪問變量 hp,因?yàn)樗赡苁撬接械?,因此最好?Rock 類創(chuàng)建 setter 和 getter 方法,然后使用它。
搖滾類:
public ROCK(int hp, int stamina, int attack, int speed, String type){
this.hp=hp;
this.stamina= stamina;
this.attack= attack;
this.speed = speed;
this.type = type;
}
public void setHP(int hp){
this.hp = hp
}
public void getHP(){
return hp;
}
然后在你的其他班級(jí)使用這個(gè):
private void Attack (ActionEvent event){
round1Rock.setHP(12); //this will update the value
}
添加回答
舉報(bào)
