how to use method on specific object from arraylist - java

EDIT2: Sorry all... I believe it is due to the lack of understanding of question that cause this misconception. After reading through, I think what they want is for the return value of getWinningPoint() be the biggest number among the players and yet still <=21. so that in the game output, can loop each player to get their card point again and compare it to this winningpoint. I thank all of your input and help. Moderator or Admin can close this thread. Thanks again.
I would like to find out how to access the particular object in the arraylist so that i can cast the method on it. In a overall view, I am able to make method that apply to all items in the arraylist of players (distributeCardsToPlayer). But my 2nd method of getWinningPoints() is a int that sum up all the cards the particular player in arraylist players have. The winningPoint is a individual result which will ultimately be used in printWinners() method. I'm only familiar with accessing a obj with "Player player = players.get(0);" but in this case the "player" itself will be calling getWinningPoints() to check their own result.
P.S - I am not sure how to put it properly,and hopefully someone can point me to the right direction.
import java.util.*;
public class ModifiedBlackJack
{
protected ArrayList<Card> gameDeck;
protected ArrayList<Player> players;
public ModifiedBlackJack(ArrayList<Player> players)
{
this.players=players;
}
public void distributeCardsToPlayers()
{
Scanner console = new Scanner(System.in);
for (Player player : players)
{
player.drawACard(getACardFromDeck());
player.drawACard(getACardFromDeck());
System.out.println(player.getName()+": " + player.toString());
System.out.print("Draw another card? (y/n): ");
char input = console.nextLine().toLowerCase().charAt(0);
if(input == 'y')
{
player.drawACard(getACardFromDeck());
}
}
EDIT2: After reading through, I think what they want is for the return value of getWinningPoint() be the biggest number among the players and yet still <=21. so that in the game output, can loop each player to get their card point again and compare it to this winningpoint.
public int getWinningPoints()
{
int wp=0;;
int point=0;
for (Player player:players)
{
point = player.getCardsPoints();
if (point>=21 && point>wp)
{
wp=point;
}
}
return wp;
}
In the Player class, there is a function for summing up all the cards point
public int getCardsPoints()
{
int point=0;
for (Card c: cards)
{
point=point+c.getPoints();
}
return point;
}
I am new to java and any help or guidance is very much appreciated.
Thank You

You may be overthinking this, and the method getWinningPoints isn't entirely required.
Because you already have getCardsPoints declared in Player, and you already have an instance of Player to work with in your loop, the only thing you realistically need to do is...invoke it.
System.out.println(player.getName() + "Chips: " + player.getChips() + "[]" + player.getCardsPoints());
Whatever conditions you need to satisfy the min parameter should be done inside of this loop; that is, conditionally print the values that are larger than min.

If you want to invoke a Player class method you need to have a player object to call a method that it "owns".
Pass the player object to the method and accept the player object in getWinningPoints().
Call
getWinningPoints(player)
Declaration
public int getWinningPoints(Player localPlayer)
{
return localPlayer.getCardsPoints();
}

Related

Is it possible to repeat external method calls by a user given times

I guess this is a simple question but I can't find an answer on either Google or Stack Overflow. I am new to Java and I hope you can help me. I'm sorry in advance if I use the wrong terminology at any point when writing my question and code.
My question is if there is any way to write a code that repeats an external method call?
The method I am calling is shootWeapon which exists in a class called Weapon. I'm calling that method from another method called shootWithWeapon which exists in a class called Soldier. My class Soldier has an inventory of weapons in ArrayList<Weapon> called weaponList. I would like to write a code that repeats listWeapon.shootWeapon() as many times as the user given shootWithWeapon parameter usedAmmo. My current code is working but it's only decreasing the ammo with 1 (since it's specified in the shootWeapon method).
This is my method in class "Soldier".
public void shootWithWeapon(String weaponChoice,int usedAmmo)
int index = 0;
while(index < weaponList.size()){
Weapon listWeapon = weaponList.get(index);
String usedWeapon = listWeapon.getName(); //returns weapon name
int xBullets = weaponList.getBulletAmount(); //returns amount of bullets in object
if(weaponChoice.equals(usedWeapon) && usedAmmo < xBullets) {
listWeapon.shootWeapon(); //This is the method I want to repeat * usedAmmo
System.out.println("Your weapon have been used. You have " + weaponList.getBulletAmount() + " bullets left".); }
index++;
}
}
This is the method I'm calling in class "Weapon".
public void shootWeapon()
{
bulletAmount=bulletAmount - 1;
}

Get object who called current object

I have a class Player, with a an object player_1, and an another class Weapon.
From my object player_1 i call a method who is located in class Weapon player_1.getWeapon().changeDurability(int x)
void changeDurability( int x) {
// changing durability
// and then i want to do something like this :
if( durability <= 0) player1.setWeaponBroken(true)
}
But i don't know how to get the player1 from the Weapon object,
and is there a way to do this instead of changing the method to something like this:
void changeDurability(Player player, int x)
Thanks in advance for any helping answers.
Whether or not a weapon is broken is information that belongs to that weapon, not to the player using it. I would recommend that you move the isBroken variable to the Weapon class and then have a method like this in your Player class:
boolean isWeaponBroken(){
return this.getWeapon().isBroken
}
You may fix your call to the player's weapon - without fixing Weapon class:
// Player code
public void changeWeaponDurability(int x) {
player_1.getWeapon().changeDurability(x);
if (player_1.getWeapon().getDurability() <= 0) {
player_1.setWeaponBroken(true);
}
}

Polymorphism example? (Substitution principle and late dynamic binding)

Below is a snippet of my code and I can’t decide whether or not it is an example of Polymorphism.
Class hierarchy 1
Within my Player class (This is a subclass of Character) there is a method called showStats().
public String showStats(){ // Displays all current stats regarding the player.
String stats = "<html><br>Name: "+ getName()+ "<br>Type: "+ getCharacterType() + "<br>Health: "+ getHealth() +"<br>Weapon Equipped: "+ getWeaponEquippedName()+"<br>Miles Walked: "+getWalked()+"<br>"+showInventory()+"<br>Level Completed: "+getLevelCompleted();
return stats;
}
This method is overridden within the Magician and Warrior classes due to exclusive statistics only Warriors and Magicians would possess if they are of that type (Warriors have a power points attribute and Magicians have a steal points attribute).
Magician Class:
public String showStats(){ // Overridden method that shows all player stats including the number of steal points.
String stats = super.showStats()+"<br>Steal Points: "+getMana()+"</html>";
return stats; }
Warrior Class:
public String showStats(){ // Overridden method that shows all player stats including the number of Power Points if they are a Warrior.
String stats = super.showStats()+"<br>Power Points: "+getMana()+"</html>";
return stats;
}
Within the class Battle I call the showStats() method and the output is not known until the User has selected what character they wish to play as. I just wanted to be certain that this is an example of polymorphism as the character selected is not known until the program has already been compiled and is then selected by the user (i.e. Substitution principle and Late Dynamic Binding).
public static void gameMenu(Player player, int choice, String name)throws FileNotFoundException, IOException, ClassNotFoundException { // Game menu method is for displaying all options (Play game, view game rules, quit) to the user when the game runs.
//Substitution principle applied to the player object depending upon what character the player wishes to select.
if (choice == 3) {
player = new Attack_Warrior();
}
else if (choice == 4) {
player = new Defensive_Warrior();
}
else if (choice == 5) {
player = new Attack_Magician();
}
else if (choice == 6) {
player = new Defensive_Magician();
}
else{
System.out.println("Error. Try again.");
play(player); // If the user enters an invalid input, the method loops and asks the player to re-enter their input.
}
Thank you very much for your time and I look forward to hearing your response,
Alex
It is helpful to annotate the method of your child classes with #Override. If you do not get a compilation error, any code written with the parent type is a proper polymorphic call ;-)

Accessing an object of a class from another class object

Starting of I want to apologise for my english as I'm not a native speaker. The title might be a bit off since I was not sure how to phrase it but hopefully it will come through once I show my code.
The problem I'm phasing is I want to use the shop class to handle any purchases while storing the money variable on the player class.
Is there any way to access the money integer of the player class without creating an object of the player class in the shop class ?
I was thinking about using a static integer to store the data in but from what I've read online its bad practice to use static datatypes.
public class Beta {
public static void main(String[] args) {
Player p1 = new Player("Test");
Shop s1 = new Shop();
p1.setMoney(100);
s1.clerk(p1.getMoney());
}
}
public class Player {
private int money;
private String name;
public Player(String name) {
this.name = name;
}
public int getMoney() {
return money;
}
public void setMoney(int x) {
this.money +=x;
}
}
public class Shop {
private int money;
public void clerk(int x) {
this.money = x;
if (this.money >= total) {
question4 = false;
System.out.println("Your purchase was successful!");
if (blue > 0) {
this.addInventory("Blue", blue);
}
if (red > 0) {
this.addInventory("Red", red);
}
if (green > 0) {
this.addInventory("Green", green);
}
}
else {
question4 = false;
System.out.println("Sorry you cant afford that!");
}
}
}
}
So I cut down my code to show you only the essential parts.
What I want to do is access p1:s money variable from the player class from within the Shop class.
So far I have been passing the variable when calling it from main. Is this the only option I have or can it be accessed in any other way ?
Any help would be much appreciated!
I believe the option that follows Object-Oriented Programming principles best is to pass the actual Player in as an argument, instead of just the money.
Basically, passing just the player's money in instead of the player themselves is like just handing your wallet over to the cashier. You wouldn't do that, right?
This way, the clerk can ask the customer if they have enough money by calling player.getMoney(), and the customer can tell them the answer.
After making the purchase, the player can remove the money from their wallet themselves when the clerk asks them to via player.setMoney().
Now, you asked in a comment about "passing the actual player as an argument without creating a new object of the player class." Java passes arguments by value, and all objects' values are simply the address that hold the information for that particular instance.
So for Player p1 in Beta, let's pretend all of p1's information is stored in a block starting at...let's say, address 21343. In this case, the variable p1 only contains that single number, 21343.
Since Java passes by value, then when you call s1.clerk(Player player), the player variable will also contain 21343. Since it's editing the items contained at the same address, you've essentially passed on p1 itself instead of creating a new Player. In short, the clerk and the main method work with the same object.
The fact that Java passes by value is also why passing just the player's money in doesn't adjust it automatically: The money is an int rather than an object. Since it's an int, when you pass it to the clerk, you're just saying "Hey, clerk, this is the amount of money being worked with." But the clerk has no idea who the money belongs to, so while it can take money, or even give it some, it's essentially just setting it down on the counter, and it's the responsibility of the player to pick it up from there when they're done. By passing in the player instead, the clerk knows who the money belongs to because it's actually asking the player how much money they have.
Another potential solution would be to make p1 and s1 static variables in the Beta class. It'd look something like this:
public class Player
{
public static Player p1;
public static Shop s1;
public static void main(String[] args)
{
p1 = new Player("Test");
s1 = new Shop();
p1.setMoney(100);
s1.clerk(p1.getMoney());
}
}
From there, you'd import the Beta class in Shop, then call Beta.p1 in Shop to access p1.
Hope this helps!

Java infinite loop in despite of statement makes condition false

I am new on Java, but my problem can be language independent.
I have a Player class and in my game logic, i have a map stores created players.
I write a method -getNext()- that returns the next player to me and it works like a charm. But in the game, players that eliminated must not get in line. So I write a new method -getNextAlive()- should return next alive (!isLoser) player. If there isn't any loser player, getNextAlive() is working but if there is, program gets in while loop and looping infinitely. In while loop I switch to next player and sure that next is alive, but I think while(p.checkLose()) not affected in while changes and give this output forever:
player: allyozturk
I can't get why this happens in this way, what should I do for skipping all isLoser players and get the next alive one? (BTW, I use libgdx ArrayMap and my map is ordered because of order of next player is importont for my game)
in-game I use:
currPlayer = currPlayer.getNextAlive();
and here my Player.java is:
public class Player{
private static int counter;
public static int alives;
private int uniqueId;
private String name;
private boolean isLoser;
.
.
.
private Player getNext(){
int index = MyGdxGame.players.indexOfKey(uniqueId);
if(++index < MyGdxGame.players.size)
return MyGdxGame.players.getValueAt(index);
else
return MyGdxGame.players.getValueAt(0);
}
public Player getNextAlive(){
Player p = getNext();
while(p.checkLose()){
p = getNext();
MyGdxGame.logger.error("player: " + p.getName()); // just for testing purpose
}
return p;
}
}
And an addition question coming from some curiosity and some for doing the best: Is it totally appropriate that using a method returns Player in the Player class?
Replace p = getNext(); with p = p.getNext();

Categories