2015-04-02 52 views
1

我想使一個變量作爲文件名。我想要一個通用的命令,當一個子類繼承時,可以設置一個文件名作爲變量。文件名是一個變量

代碼編譯只是好玩,但是當我運行它,我按d或移動的化身,我收到了popupwindow說找不到文件的關鍵:avatarRight

編輯:如果我從刪除引號參數列表並初始化正上方,然後將文件名運行,但我希望能夠初始化變量在子類中,使多個子類可以有不同的圖像

超類方法:

/** 
* Sets up the movement keys and facing for the Object 
*/ 
public void movement() 
{ 
    String avatarRight = "Alien.png"; 
    String avatarLeft = "Alien1.png"; 

    if (atWorldEdge() == false) 
     { 
     if (Greenfoot.isKeyDown("w")) 
     { 
      setLocation(getX(), getY()-1); 
     } 
     if (Greenfoot.isKeyDown("d")) 
     { 
      setImage(avatarRight); 
      setLocation(getX()+1, getY()); 
     } 
     if (Greenfoot.isKeyDown("s")) 
     { 
      setLocation(getX(), getY()+1); 
     } 
     if (Greenfoot.isKeyDown("a")) 
     { 
      setImage(avatarLeft); 
      setLocation(getX()-1, getY()); 
     } 
     } 
    else 
     { 
     } 
} 

子類:

public class Alien extends Living 
{ 
    private String avatarRight = "Alien.png"; 
    private String avatarLeft = "Alien1.png"; 
    /** 
    * Act - do whatever the Alien wants to do. This method is called whenever 
    * the 'Act' or 'Run' button gets pressed in the environment. 
    */ 
    public void act() 
    { 
     movement(); 
    }  
} 
+0

你有什麼問題? – 2015-04-02 23:29:31

+0

該代碼編譯只是有趣的,但當我運行它,我按d或一個鍵來移動頭像我得到一個popupwindow說 找不到文件:avatarRight – power5000 2015-04-02 23:31:48

+0

你應該編輯你的問題,並把它的問題描述 – 2015-04-02 23:33:28

回答

0

相反聲明方法movement內的圖像變量,而不是宣稱要將class內使用,並且變量傳遞到您要使用它的方法之一。的

所以不是這樣:

public void movement() 
{ 
String avatarRight = "Alien.png"; 
String avatarLeft = "Alien1.png"; 
... 

這:

public class Alien extends Living 
{ 
    private String avatarRight = "Alien.png"; 
    private String avatarLeft = "Alien1.png"; 
    /** 
* Act - do whatever the Alien wants to do. This method is called  whenever 
* the 'Act' or 'Run' button gets pressed in the environment. 
*/ 
public void act() 
{ 
    movement(); 
}  
} 

這樣做:

public void movement(String avatarLeft, String avatarRight) 
{ 
... 

這:

public class Alien extends Living 
{ 
    private String avatarRight = "Alien.png"; 
    private String avatarLeft = "Alien1.png"; 
/** 
* Act - do whatever the Alien wants to do. This method is called   whenever 
* the 'Act' or 'Run' button gets pressed in the environment. 
*/ 
public void act() 
{ 
    movement(avatarLeft, avatarRight); 
}  
} 

這將允許您將不同的圖像從不同的頭像類傳遞到移動方法。