Iterating a loop through all objects of a class - java

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.

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).

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.

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.

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;

Related

java how to add variables to an object from a string

I have two objects that are being stored in arrays:
Game(String creator, String title, int releaseYear, int NumberSold)
Creator(String name, String gamesWorkedOn)
Game(creator) has multiple creators, so is stored as a string like this: "creator1, creator2, creator3" using commas to separate their values.
Not all games have multiple creators and there are not many different creators in total.
What I am trying to do is loop through an array of Game(games) and extract a creator variable from it and assign it to the Creator(name) and then match any games that creator is mentioned in and assign those title variables to Creator(gamesWorkedOn).
So far I have this:
public static void PopulateCreators(ArrayList<Game> games) {
//populating an array of Creators with games they have worked on
boolean match = false;
String thisCreator;
String gamesWorkedOn;
ArrayList<Creator> creatorArray = new ArrayList<Creator>();
for (int i = 0; i < games.size(); i++) {
thisCreator = games.get(i).getGameCreator();
thisCreator = thisCreator.replaceAll(", ", "\n");
Which gives me this output using a sysout:
Shigeru Miyamoto
Satoshi Tajiri
Yoshiaki Koizumi
Koichi Hayashida
Shigeru Miyamoto
My desired output would be to have something like this:
name = "Shigeru Miyamoto"
gamesWorkedOn = "game1, game2, game3"
I am looking at using a for loop but am unsure on how to implement it here.
Edit:
I forgot to mention a couple of details that I didn't think were important but I will be a bit clearer now. This is a Swing based project I am working on that takes user inputs and stores these arrays which are then saved into a JSON file that is read upon loading of the application and when a user clicks a 'save' button.
What you seem to want to do is map the creators to all the games that they have created or helped create. I'm going to start by creating a simplified version of the problem.
You have a list of:
class Game {
Set<Creator> creators;
}
which you want to convert to:
Map<Creator, Set<Game>> createdGames; // Map of creator name to games created
The first thing to do here is to find all of the unique creators to start adding to the map. This can be done with the stream API.
createdGames = gameList.stream().flatMap(game -> game.creators.stream()).distinct().collect(Collectors.toMap(Function.identity(), v -> new HashSet<>()));
Now you can just loop through all the games again and add the game to a creator's set if they took part in the creation of that game.
for(Game game : gameList) {
for(Creator creator : createdGames.keySet()) {
if(game.creators.contains(creator)) {
createdGames.get(creator).add(game);
}
}
}

Simple variable reference

So I'm currently trying make a simple rpg game, it's my first time so I'm learning haha, but my question is that, I am trying to reference a variable in another class I have for the player's choice of their class. P.S. I couldn't figure out what to look up so I'm sorry if this is a repeat question.
this is the main
public static void main(String[] args) {
Scanner inputRace = new Scanner(System.in);
player player1 = new player(race.valueOf(inputRace), profession.ranger);
}
and here is the race class I'm trying to reference
public enum race {
orc, elf, human, dwarf
}
So all I'm trying to do is be able to take the user's input and do like race.("whatever their choice is"), but I haven't been able to figure it out. Thanks for any help and sorry if it's confusing.
In other to access input data you must use scanner methods like next, nextInt, nextDouble etc.
In your case you are looking for string so it should look like this:
try {
Race race = Race.valueOf( inputRace.next() ); // next returns string
Player player1 = new Player(race, profession.ranger);
} catch ( IllegalArgumentException ex ) {
System.err.println( "That race doesn't exsist" );
}
Note that I used upper case for Race and Player, this is standard way of naming your classes.
Also you should put your code in some kind of loop until he doesn't write correct race.
If I understand correctly, you need to get race.orc if the user enters orc, and henceforth.
You're on the right track, you just need to input the String from the user, like
String s = inputRace.next();
player player1 = new player(race.valueOf(s), profession.ranger);

Java Not Using a parameter of the same class in a method

I have the following method inside the class Player that uses one of his emporiums available and sets it on a determined City
public void setEmporium(City city){
Emporium emporium = getEmporiums().get(0);//gets the emporium from the player
city.getEmporium().add(emporium);//adds it to the city
LinkedList<Bonus> bonus = city.getBonus();
for (int i=0;bonus!=null&&i<bonus.size();i++){
bonus.get(i).applyBonus(player);//Error line
}
getEmporiums().remove(0);//removes the emporium from the player
}
To correct the error of course i can just use the parameter player like this
public void setEmporium(City city,Player player){
but it isn't kind of redundant to use a parameter in its same class?
because when i test it would be like
Player player = new Player(1);
City city = new City(CityName.BURGEN,Color.YELLOW,4);
player.setEmporium(city, player);
and if i would create another object i would be able to do this
Player player2 = new Player(2);
player2.setEmporium(city, player);
This would mean that another player could build using emporiums from another player which shouldn't be possible, a player can only build using its own emporiums.
The only other solution that eclipse gives me is to create a local variable Player player; but then it says that it's not initialized, is there another way?

Java Object Instance creation problems

So I've been struggling all day today trying to create an instance of a class called 'Sport'.
I've got my code set up so I run the User Interface, which then runs a constructor, which then runs another constructor which loads the Sport values from a text file.
The problem is, the way I'm apparently creating the objects is wrong. Could really use some help.
public static void seperateValues(String sportDetail)
{
String[] sportDetails = sportDetail.split(",");
System.out.println("Adding new sport to the Sport collection");
System.out.println(sportDetail);
/*
for(int i=0; i<sportDetails.length; i++) //just used for testing whether it was splitting correctly
{
System.out.println(sportDetails[i]);
} */
// name,usagefee,insurance,affiliationfees, then court numbers
//Tennis,44,10,93,10,11,12,13,14,15,16
int vlength;
vlength = sportDetail.length();
String[] sportDetailz;
sportDetailz = new String[vlength];
sportDetailz[0] = sportDetails[0]; //name
sportDetailz[1] = sportDetails[1]; //usage fees
sportDetailz[2] = sportDetails[2]; //insurance
sportDetailz[3] = sportDetails[3]; //afflcationfees
String vSportObjectName;
vSportObjectName = sportDetails[0];
String sportinstance;
sportinstance = sportDetails[0]; //this is the name of the sport which I'm hoping each loop around
//it will give a new name to
Sport sportinstance = new Sport(sportDetails);
//System.out.println(Sport.this.name);
}
Error message: variable sportinstance is already defined in method seperateValues(java.lang.String)
http://puu.sh/2zil9
I'm guessing your issue is that you first declare sportinstance as a String. You then try to define it again as a Sport.
Just remove the following lines and try again (as it doesn't look like they actually are used anywhere else):
String sportinstance;
sportinstance = sportDetails[0];
The other option would be to simply rename either one of your instances of sportinstance.
You are trying to define sportinstance as two different datatypes and Java will not allow this. Either change the name of the Sport definition of sportinstance to another variable name or remove the definition.

Java - Error in eclipse: the left hand side of an assignment must be a variable

This is a small part of my code. My project is to simulate a whole school system. To add teachers, courses etc. All of my class members are private, so i created setters and getters methods. I try to give to 'teachersNum' a value and this must be automatic(not from keyboard). So i want to give it value 1 if its the first teacher etc. I hope you can understand. Sorry for my English.
public void addTeachersList(Teachers teachers) {
if(this.teachersSize<100){
this.teachersList[this.teachersSize] = teachers;
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
this.teachersSize++;
}
}
You'll have to call a setter:
this.teachersList[this.teachersSize].setTeacherNum(this.teachersSize-1);
Calling the getter getTeacherNum just gives you the number, it isn't a reference to that property.
Although I must say, you'd really do yourself a favor by using a List implementation instead of arrays.
In this line
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
getTeacherNum() returns a value. You can't assign to it.
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg:
temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003
You have the problem here
this.teachersList[this.teachersSize].getTeacherNum() = this.teachersSize -1;
.getTeacherNum() will return a value which must be stored in a variable on left side.
eg: temp = .getTeacherNum();
And its better to use a static variable to keep the count of teachers, so every time a teacher is created he/she gets a nos which is different from the previous one
eg:
xxxx001
xxxx002
xxxx003

Categories