[英]Accessing public variables in the main class within other classes
我正在嘗試將用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
};
據推測,當將要分類的兩個類一起編譯時,該程序將能夠運行,因為主要變量是公共變量,而播放器變量是在程序運行時定義的。 但是,編譯器無法識別這一點,並且會引發錯誤,因為類(順便說一句,在同一目錄中)不會互相讀取,並且在檢查數組/數組列表時沒有“定義”對象。
如何獲得已定義的編譯器可見的變量? 我可以上傳這兩個類的當前工作版本以及最終的python版本(如果需要),但是我想保持我的游戲為開源。
編輯:根據sjkm的回復修復了ArrayList初始化
定義列表的通用類型:
更改
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>();
否則,您總是必須轉換從列表中獲得的對象...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.