PocketLoan
PocketLoan

Reputation: 532

Iterating a loop through all objects of a class

New to Java- I'm building a poker program and I've created a player class with some instance variables including "toppair", "highcardst",etc... I tried to use a placeholder variable to refer to the appropriate player's instance variable rather than relying on if statements.

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;**

I receive an error on that last line- it looks like java doesn't accept this syntax. Essentially, since this hand is a straight I want to append the value of the "highcardst" instance variable of the "n" th player as n hands have been dealt.

Thank you.

Upvotes: 0

Views: 91

Answers (4)

Bruce
Bruce

Reputation: 8849

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

Error is here. place holder is String type not Player type. Make temp variable as Player variable and assign

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

Upvotes: 0

Tadas
Tadas

Reputation: 81

You could make a list of players and get the instance of the player from the list as required.

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

Or something like that.

Upvotes: 1

riccardo.cardin
riccardo.cardin

Reputation: 8353

I think the problem could be in this statement:

placeholder.highcardst=straightHigh;

You've defined placeholder of type String, so the property called highcardst does not exist.

Upvotes: 0

khelwood
khelwood

Reputation: 59146

You seem to be uses a String for your placeholder variable where you actually want to refer to a player object.

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;

Also, it will make your code easier to follow if you follow normal Java code conventions, such as capitalising the first letter of a class name (e.g. Player, not player).

Upvotes: 2

Related Questions