2015-04-01 162 views
0

新的所有對象的循環,以Java的 我要建一個撲克計劃,我已經創建了一個播放器類的一些實例變量,包括「toppair」,「highcardst」,等等。我試圖使用佔位符變量來引用合適的玩家的實例變量,而不是依賴if語句。迭代通過類

int handsdealt=0; 
int straightval=0; 
String placeholder="blank"; 
player playerone = new player("Richard"); 
player playertwo = new player("Negreanu"); 
//code omitted 
if (handsdealt==1) placeholder="playerone"; 
else placeholder="playertwo"; 
//code to determine if hand is a straight -if it is it sets straightval to 1 
**if(straightval==1) placeholder.highcardst=straightHigh;** 

我在最後一行收到一個錯誤 - 它看起來像java不接受這種語法。基本上,由於這隻手是筆直的,我想在n手牌發出時追加第n個牌手的「highcardst」實例變量的值。

謝謝。

+0

請發佈確切的錯誤。 – Carcigenicate 2015-04-01 10:55:00

+0

你不能使用變量作爲對象namae – Burusothman 2015-04-01 10:55:03

+0

似乎你想在Java代碼中使用JSON。最接近你想要做的是Map.put(...,...); – ControlAltDel 2015-04-01 10:56:18

回答

1

您可以根據需要製作玩家列表並從列表中獲取玩家實例。

List<player> players = new ArrayList<player>(); 
players.add(new player("Richard")); 
players.add(new player("Negreanu")); 
if(straightval==1) { 
    players.get(handsdealt).highcardst=straightHigh; 
} 

或類似的東西。

+0

是的,這種方法有利於不同數量的玩家 - 我可以處理許多手中的元素,數組列表。 – 2015-04-01 19:17:35

2

您似乎在使用String作爲您的placeholder變量,您實際上想要引用player對象。

player playerone = new player("Richard"); 
player playertwo = new player("Negreanu"); 
//code omitted 
player placeholder; 
if (handsdealt==1) placeholder=playerone; 
else placeholder=playertwo; 
//code to determine if hand is a straight -if it is it sets straightval to 1 
if(straightval==1) placeholder.highcardst=straightHigh; 

而且,它會讓你的代碼更容易,如果你遵循正常的Java代碼約定,比如大寫一個類名(例如Player,不player)的第一個字母跟隨。

+0

謝謝,我得到了一個通知來初始化對象,所以我在第4行的代碼是[player placeholder = null;] – 2015-04-01 11:09:34

0

我想問題可能是在此聲明:

placeholder.highcardst=straightHigh; 

您已經定義String類型的placeholder,所謂highcardst的屬性不存在。

0
if(straightval==1) placeholder.highcardst=straightHigh; 

錯誤在這裏。佔位符是String類型不是Player類型。使臨時變量作爲播放器變量並分配

Player placeholder; 
if (handsdealt==1) placeholder=playerone;