2015-04-01 205 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;