How to access an array index of an Object instance - java

Good day!
I am wondering How can I access an array index of an Object instance.
My code is as follows:
public class PokerPlayer {
private String name = null;
private Card [] cardsOnHand = new Card[5];
//getter and setter
}
What i want is to access the cardsOnHandArray[index] so that i can call it on another class and set the values per index...
public class PokerGame {
public static void main (String [] Args){
PokerPlayer players []= new PokerPlayer[4];
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
//ACCESS cardsOnHand index i and store something on it...
}
}
}
}
Any advice would be highly appreciated. How can i also improve my OO design? Thank you in advance

public class PokerPlayer {
...
public Card getCard(int index) {
return this.cardsOnHand[index];
}
public void setCard(int index, Card card) {
this.cardsOnHand[index] = card;
}
...
}
then use:
player.getCard(i);
player.setCard(i,new Card());

You almost have it. Just call this inside your inner loop:
cardsOnHand[i] = new Card();
Of course, change what is being assigned to the array according to your requirements.

you can do as:
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
Card[] cards= player[i].getCardsOnHand();
cards[i] = new Card();
}
}

This should work:
public class PokerGame {
public static void main (String [] Args){
PokerPlayer players []= new PokerPlayer[4];
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
Card card = player.cardsOnHand[i];
}
}
}
}

Since your cardsOnHand array is private, you have to use your (unprovided) setter function.
Which could be something like
public void setCard(int index, Card value){
cardsOnHand[index] = value;
}
And in used in your loop as
player.setCard(i, something)

Assuming that your PokerPlayer has a getter for the cardsOnHand array:
public class PokerGame {
public static void main (String [] Args){
PokerPlayer players []= new PokerPlayer[4];
for(PokerPlayer player : players){
for(int i =0; i<5; i++){
player.getCardsOnHand()[i] = new Card();
}
}
}
}
However, I think that a better solution is to add a method
public void setCard(Card card, int index) {
assert index < 5;
cardOnHands[index] = card
}
to your PokerPlayer.

Related

Card Game issue in Java

In my code I cannot find a way to assign my human and dealer variables in my method PlayGame() to their respective strings that are made from DealCards().
Whenever I run javac I get an error String[] cannot be converted to String. I don't understand this however because they are separate strings in the dealerOther array in the method DealCards(). Could someone please give me some help on this issue.
import java.util.Random;
public class GAME_8315085 {
static Random rand = new Random();
public static String[] MakeDeck() {
String[] deck=new String[51];
int k=0;
String[] suits={"\u2660", "\u2661", "\u2662", "\u2663"};
String[] ranks={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
for (int i=0;i<suits.length;i++) {
for (int j=0;j<ranks.length;j++) {
if (suits[i].equals("\u2663") && ranks[j].equals("Q")) {
;
}
else {
deck[k]=ranks[j]+suits[i];
k++;
}
}
}
return deck;
}
public static void ShuffleDeck(String[] deck) {
for (int i=0;i<deck.length;i++) {
int random = rand.nextInt(deck.length);
String tmp=deck[i];
deck[i] = deck[random];
deck[random]=tmp;
}
}
public static String[][] DealCards(String[] deck) {
String[][] dealerOther = new String[2][26];
int j=0;
for (int i=0; i<=deck.length;i+=2) {
dealerOther[0][j]=deck[i];
j++;
}
j=0;
for (int i=1; i<deck.length;i+=2) {
dealerOther[1][j]=deck[i];
j++;
}
return dealerOther;
}
public static void PlayGame() {
String[] deck = MakeDeck();
ShuffleDeck(deck);
String[][] tmp=DealCards(deck);
String human=tmp[0];
String dealer=tmp[1];
}
public static void main(String[] args) {
PlayGame();
}
}
Problem is here
String[][] tmp=DealCards(deck);
String human=tmp[0];
String dealer=tmp[1];
Since tmp is array of arrays of string(kind of 2-D array), the human and dealer has to be array of strings.
Change it to
String[][] tmp=DealCards(deck);
String[] human=tmp[0];
String[] dealer=tmp[1];

Iterating through an array and printing each object

My array is being loaded and is printing the cards out as planned (in the order they appear in the file). When I try to cycle back through the arraylist in a separate method to check whether or not the data is there, it only prints the last object rather than each of them. Can anybody tell me why?
The load method
public class
TestFrame {
//VARIABLES
private static Deck deck;
private static Card card;
private static Scanner scan;
private final static String fileName = "cards.txt";
static ArrayList<Card> cards = new ArrayList<>();
private static void Load(){
deck = new Deck();
card = new Card();
// Load in the card file so that we can work with the data from cards.txt internally rather than from the file constantly.
try(FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
Scanner infile = new Scanner(br)){
int numOfCards = infile.nextInt();
infile.nextLine(); // Do we need this? Yes we do. Illuminati confirmed.
for(int i=0; i < numOfCards; i++){
String value = infile.nextLine();
String suit = infile.nextLine();
Card newCard = new Card(value, suit);
card.addCard(newCard);
System.out.print(newCard.getValue());
System.out.print(newCard.getSuit());
System.out.println(" ");
//Print out the object before cycling through again so we can see if it's working
//We can use this to add then cards to the shuffle array at a later date
}
}
Which prints out this when ran:
ah
2h
3h
4h
5h
6h
7h
8h
etc etc. This is the order they're in the .txt file.
I then use these methods to display all of the cards to make sure I can manipulate the data elsewhere
private static void displayAllCards(){
Card[] cards = Card.getAll();
for(Card c : cards){
System.out.print(Card.getValue());
System.out.print(Card.getSuit());
System.out.println(" ");
}
}
and the getAll() method
public static Card[] getAll(){
Card[] brb = new Card[cards.size()];
int tempCount = -1;
for(Card c : cards){
tempCount++;
brb[tempCount] = c;
}
return brb;
}
When getAll() is ran, it only prints out "ks" (king of spades) which is the last card in the .txt file. Can anybody tell me why this is happening?
Thanks
EDIT: CARD CLASS
package uk.ac.aber.dcs.cs12320.cards;
import java.util.ArrayList;
public class Card {
protected static String value;
protected static String suit;
static ArrayList<Card> cardsList = new ArrayList<>();
public Card(String v, String s){
this.value = v;
this.suit = s;
}
public Card() {
}
public static Card[] getAll(){
Card[] brb = new Card[cardsList.size()];
int tempCount = -1;
for(Card c : cardsList){
tempCount++;
brb[tempCount] = c;
}
return brb;
}
public static void deleteAll(){
cardsList.clear();
}
public static String getValue() {
return value;
}
public void setValue(String value) {
Deck.value = value;
}
public static String getSuit() {
return suit;
}
public void setSuit(String suit) {
Deck.suit = suit;
}
public void addCard(Card card){
cardsList.add(card);
}
}
card.addCard(newCard);
I think this should be cards.addCard(newCard); instead
Your card class is not implemented well. The reason you are getting only the last value is because your getters and String variables are static. There is only one copy of static variable per class. You need to make those instance variables/methods and change your print loop to
for(Card c : cards){
System.out.print(c.getValue());
System.out.print(c.getSuit());
System.out.println(" ");
}
See this answer for an elaboration on static vs instance
In Card the variables suit and value are declared static. This means that there is only one variable, shared between all cards.
When you load, you create a card. You set suit and value So they get h and a respectively. And then you print them.
Then you load the next two lines. You create a new card. But the variables are static, not part of the state of the new object, but the same suit and value that contain h and a. The new value is 2. And it replaces the a. Then you print it. The old value is gone.
So your print in the load shows the momentary value of suit and value, but in truth, there is only one value - the last value you loaded from the file.
These variables should be part of the card's state, thus, not static!
Note: your IDE notices when you try to use an instance variable from a static context. For example, your getValue method is static. So it can't access instance variables. However, the correction is not to set the variable to static, but rather to change the method, which logically is supposed to be an instance method, to not static. It may complain again because you are calling the method from static context. Then you have to carefully look why: you are not supposed to use this method statically - you should create an instance of Card and call the method using the variable you created.
So, IDE suggestions to "make it static" are not the correct solution! You should make all instance-related variables and methods not static, and solve "static context" issues by checking why you didn't create an instance and decided to call an instance-related method statically instead.
card.addCard(newCard); looks like it could be cards.add(newCard); and also a tip, changing your indexing looks a bit nicer when you start at zero for the getAll function
public static Card[] getAll(){
Card[] brb = new Card[cards.size()];
int tempCount = -1;
for(Card c : cards){
tempCount++;
brb[tempCount] = c;
}
return brb;
}
change it to
public static Card[] getAll(){
Card[] brb = new Card[cards.size()];
int tempCount = 0;
for(Card c : cards){
brb[tempCount] = c;
tempCount++;
}
return brb;
}
You are calling getAll() on a specific card, however before when you had card.addCard, you would only be adding one card to the list since every Card has its own ArrayList. This is why it only would print ONE CARD. You need to use getAll() on the ArrayList you made in the file.
Make a getAll() method in the main file that uses static ArrayList<Card> cards = new ArrayList<>();
public static Card[] getAll(){
Card[] brb = new Card[cards.size()];
int tempCount = 0;
for(Card c : cards){
brb[tempCount] = c;
tempCount++;
}
return brb;
This will work.

Filling an array with objects

I need some help with a homework question I am working on.
I need to create a "Library" class that contains an array of Song objects.(capacity of 10).
Then make a method addSong.
Here's what I have so far:
public class Library{
Song[] arr = new Song[10];
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
}
My question is: Is there another way to fill the array? i will later need to search for a song based on a index value. So i will create a method like:
public Song getSong(int idx)
Thank you in anticipation for your answers!
If you really have to use an array (and not an ArrayList or LinkedList), this solution may be the right for you:
public class Library{
private Song[] arr = new Song[10];
private int songNumber = 0; //the number of Songs already stored in your array
public void addSong(Song s){
arr[songNumber++] = s;
}
}
If you want to avoid a runtime-exeption if you add more then 10 songs:
public void addSong(Song s){
if(songNumber<10)
{
arr[songNumber++] = s;
}else{
//what to do if more then 10 songs are added
}
}
There are a number of ways of accomplish this.
The logic you're using is more or less ok.
But what you are doing here:
public void addSong(Song s){
for(int i=0; i<10; i++)
arr[i] = s;
}
Is filling all the Songs array with the same song, perhaps this would be better:
public void addSong(Song s, int index){
arr[index] = s;
}
Of course, if you pass a negative index, or an index greater than 9, you are gonna be in trouble.
Use an ArrayList instead of an array. This way you can use the ArrayList.add() function to append to the end of your array and the ArrayList.get(int index) function to get the array entry at index index.
public class Library{
ArrayList<Song> arr = new ArrayList<Song>();
public void addSong(Song s){
arr.add(s);
}
public Song getSong(int index){
return arr.get(index);
}
}
To expand on Vacation9s' answer:
ArrayList<Song> songArray = new ArrayList<Song>();
public void addSong(Song s){
songArray.add(s);
}

Null pointer exception for Array of Objects

I am new to using arrays of objects but can't figure out what I am doing wrong and why I keep getting a Null pointer exception. I am trying to create an Theatre class with an array of spotlight objects that are either set to on or off. But - whenever I call on this array I get a null pointer exception.
package theatreLights;
public class TheatreSpotlightApp {
public static void main(String[] args) {
Theatre theTheatre = new Theatre(8);
System.out.println("element 5 " + theTheatre.arrayOfSpotlights[5].toString());
}
}
package theatreLights;
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i].turnOn();
}
}
}
package theatreLights;
public class spotlight {
int state;
public spotlight(){
state = 0;
}
public void turnOn(){
state = 1;
}
void turnOff(){
state = 0;
}
public String toString(){
String stringState = "";
if(state == 0){
stringState = "is off";
}
else if(state==1){
stringState = "is on";
}
return stringState;
}
}
I must be doing something basic wrong in creating the array but can't figure it out.
replace
arrayOfSpotlights[i].turnOn();
with
arrayOfSpotLights[i] = new Spotlight();
arrayOfSpotlights[i].turnOn();
The line
arrayOfSpotlights = new spotlight[N];
will create an array of spotlights. It will however not populate this array with spotlights.
When you do "arrayOfSpotlights = new spotlight[N];" you init an array of length N, what you need to do is also init each object in it:
for i=0; i<N; i++
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
Hope I'm correct :)
You are not creating an spotlight objects.
arrayOfSpotlights = new spotlight[N];
This just creates an array of references to spotlights, not the objects which are referenced.
The simple solution is
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i] = new spotlight();
arrayOfSpotlights[i].turnOn();
}
BTW You should use TitleCase for class names.
You could write your class like this, without using cryptic code like 0 and 1
public class Spotlight {
private String state;
public Spotlight() {
turnOff();
}
public void turnOn() {
state = "on";
}
void turnOff() {
state = "off";
}
public String toString() {
return "is " + state;
}
}
You declared the array arrayOfSpotlights, but didn't initialize the members of the array (so they are null - and you get the exception).
Change it to:
public class Theatre {
spotlight[] arrayOfSpotlights;
public Theatre(int N){
arrayOfSpotlights = new spotlight[N];
for (int i = 0; i < arrayOfSpotlights.length; i++) {
arrayOfSpotlights[i]=new spotlight();
arrayOfSpotlights[i].turnOn();
}
}
}
and it should work.

storing command line args in an array class

Musical Chairs. Musical Chairs is a children’s game where the players walk around a group of chairs while some music is playing. When the music stops, everyone must sit down. But, there is one less chair than there are people, so someone gets left out. And, indeed, that person is out of the game. A chair is removed. And the game is played again; someone else goes out. This continues until there is only one player left, the winner.
I am having problems storing the command line arguments in the player[]
here is my code
import java.util.*;
public class MusicalChairs {
Player [] players;
Random r = new Random();
public static void main(String[] args){
MusicalChairs mc = new MusicalChairs();
mc.setUpGame(args);
}
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
}
}
public void showStatus(){
}
public void winner(){
System.out.println("is the winner");
}
}
class Player{
enum Status{IN,OUT};
private String name;
private Status status;
public Player(String n){
name=n;
}
public String getName(){
return name;
}
public void setStatus(Status s){
status=s;
}
public Status getStatus(){
return status;
}
public String toString(){
String ret = name;
if(status==Status.IN){
ret="IN ";
}
else{
ret="OUT ";
}
return ret;
}
}
You're not storing the arguments in your array. If your question is how to do it, then you should:
Initialize the players array.
For each argument, you must create a Player object and store it in the array.
Use the data in your program.
This could be done like this:
public void setUpGame(String [] p) {
System.out.println("This is how we stand.......");
//Initialize the `players` array.
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
//For each argument, you must create a `Player` object and store it in the array.
players[i] = new Player(p[i]);
players[i].setStatus(Status.IN);
}
//Once your array is filled, use the data in your program.
//...
}
The question is still open: What's your specific problem?
I think you need to update your code to create new players and maintain the reference in your array...
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
// You may want to check for a 0 number of players...
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
players[i] = new Player(p[i]);
players[i].setStatus(Player.Status.IN);
System.out.println(players[i].getName()+" is "+ players[i].getStatus());
}
}

Categories