4 回答

TA貢獻1852條經驗 獲得超1個贊
當你定義
private void continueRound1 (ActionEvent event){
ROCK round1Rock= new ROCK( 500, 100, 100, 100, "Metamorphic");
}
您ROCK round1Rock只是為函數定義continueRound1。要Attack訪問該對象,您需要round1Rock在類級別上進行定義。
嘗試:
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貢獻1865條經驗 獲得超7個贊
在類級別定義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貢獻1865條經驗 獲得超7個贊
而不是在 continueRound1 方法中創建一個新的 Rock 對象。您可以在類范圍內創建新的 Rock 對象并設置私有訪問。這將解決您的問題。
附加提示:每次單擊按鈕時,您都會創建一個新對象。如果我編寫程序無限期地單擊按鈕,這將導致OutOfMemoryError 。
以下是我避免此問題的見解:
我假設每個客戶都需要新的搖滾樂。因此,在客戶端類中創建一個 Empty Rock 對象。
在您的客戶端構造函數中,您可以使用巖石類型的默認值初始化巖石對象。getDefaultRockForType 將幫助您創建任意數量的巖石類型。因此,我們將客戶端類中帶有一些值的 Rock 對象的實現細節隱藏為 Rock 類中的標準化值。
這是我的代碼片段:
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 類中,您可以提供由您的巖石類型決定的默認值。
類搖滾:
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貢獻1790條經驗 獲得超9個贊
首先像這樣聲明 ROCK 的實例是全局的
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 動作偵聽器中,您可能無法訪問變量 hp,因為它可能是私有的,因此最好為 Rock 類創建 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;
}
然后在你的其他班級使用這個:
private void Attack (ActionEvent event){
round1Rock.setHP(12); //this will update the value
}
添加回答
舉報