filename是一个变量

时间:2015-04-02 23:24:12

标签: java variables filenames greenfoot

我正在尝试将变量作为文件名。我想要一个通用命令,当子类继承时,可以将文件名设置为变量。

代码编译很有趣但是当我运行它并按d或键移动头像我得到一个弹出窗口说无法找到文件: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();
    }    
}

1 个答案:

答案 0 :(得分: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);
}    
}

这将允许您将不同的图像从不同的头像类传递给移动方法。