访问其他类中的主类中的公共变量

时间:2013-09-30 16:52:49

标签: java variables compiler-errors

我正在尝试将我用Python制作的游戏移植到Java。在Python版本中,我将所有方法和变量放在一个“类”中,并且播放器是这样的字典:

game.py

...
new_player={"name":"","hp":0,...}
players=[]
//to add new player
players.append(new_player.copy())

然后单独添加玩家的数据值:

...
players[0]["name"]="bob"
players[0]["hp"]=50
...

在Java版本中,我有一个单独的类用于定义Player对象,以及游戏的主要方法。

例如(这是一个小版本):

game.java(返回省略)

import java.utils.*;
public class game
{
    public static ArrayList<player> players = new ArrayList<player>();
    public static ArrayList<String> pdead = new ArrayList<String>();
    public static int turn = 0;
    public static void main(String[] args)
    {
        //do stuff
        players.add(new player(name));
        //do other stuff
    }
    public static void do_move(move)
    {
        //some move is selected
            players.get(turn).set_hp(10);
            //at this point compiler throws error: cannot find symbol
            //compiler does not recognize that a player should have
            //been added to the players variable
        //other stuff
    };
};

player.java(返回省略)

public class player
{
    //arbitrary list of private variables like hp and name
    public player(new_name)
    {
        name = new_name;
        //other variables defined
    };
    public void set_hp(int amount) //Adding hp
    {
        hp += amount;
    };
    public void set_hp(int amount,String type) //taking damage
    {
        mana += amount;
        //go through types, armor, etc.
            hp -= amount;
    };
    public void display stats() //displays all player's stats before choosing move
    {
        //display stats until...
        //later in some for loop
            System.out.println(players.get(index).get_hp());
            //here compiler throws error again: cannot find symbol
            //players arraylist is in main class's public variables
        //other stuff
    };
    //other stuff
};

据说,当两个要编译的类一起编译时,程序将能够运行,因为主变量是公共的,并且随着程序的继续定义了播放器变量。但是,编译器无法识别并抛出错误,因为类(在同一目录中,顺便说一下)不会相互读取,并且在检查时数组/ arraylist中没有“定义”对象。

如何让编译器看到变量?如果需要,我可以上传这两个类的当前工作版本和最终的python版本,但我喜欢让我的游戏保持封闭源代码。

编辑:根据sjkm的回复修复ArrayList初始化

1 个答案:

答案 0 :(得分:0)

定义列表的通用类型:

变化

public static ArrayList players = new ArrayList<player>();
public static ArrayList pdead = new ArrayList<String>();

public static ArrayList<player> players = new ArrayList<player>();
public static ArrayList<String> pdead = new ArrayList<String>();

否则你总是要从列表中投射出来的对象......