[Java] More help needed (arraylists, getting etc.) :/

Nenad

~Choco Coronet~ Omnomnom
Reaction score
137
Create a class Card

String field suit in public class Card in package x
A card has a suit. The suit can either be Clubs, Hearts, Spades or Diamonds. We let each be denoted by a capital letter; "C", "H", "S" or "D", respectively.

int field face in public class Card in package x
The face is the value of the card. For our purposes, let Ace have the value 1, and then let the rest of the cards have their conventional values.

public String method toString in public class Card in package x
The toString method returns the suit and face values as one String with no space in between.

Example: The Ace of Spades should return "S1" as the value of the toString method.

Create the class CardDeck. The card deck will obviously hold some cards later on.

ArrayList<Card> field cards in public class CardDeck in package x
A CardDeck is effectively a list of Cards. Create such an list field.

public void method init in public class CardDeck in package x
The init() method fills the deck with the 52 cards that are in a standard deck. Fill it in the order S,H,D,C and in increasing face value, i.e. the first card is the Ace of Spades ("S1"), the second 2 of Spades ("S2"), and the last is King of Clubs ("C13").

public Card method getCard in public class CardDeck in x
Create a method that takes an int argument and returns the card in that position in the Card list.

This is another part of the assignment that is still not going well, several questions here if anyone can help me:

1. What the **** is that toString method supposed to do? This is all of the assignment and frankly i don't even know where to start on that one.
2.
This is my code for the CardDeck part:
Code:
import java.util.ArrayList;

public class CardDeck {

	private ArrayList<Card> cards;
	
	 public void init() 
		{
		String S[] = {"S", "H", "D", "C"};
		String Card[] = new String[51];
		int z = 0;
		for (int i=0; i==S.length;i++)
		{
			for (int j=1; j<=13; j++)
				{
				Card[z]= S[i]+j;
				z=z+1;
				}
		}
		}
		
	 public Card getcard(int n)
	 {
		return cards.get(n);
	 }

}

Now, the first method is not yet finished because i had trouble with the add method to add the Cards to the list. How do i do this properly (i always have an error when i try cards.add(Card[z]) ). As it says it needs to be in order, so i figured this way is the easiest to do it but i'm not sure.

3. Is the final method, that is getCard, correct? I'm still learning the get set and stuff like that so i'm not quite sure on that one.

Thanks for all the help again ^^
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
Code:
import java.util.ArrayList;

public class Card {

    private String suit;
    private int face;
    
    public Card(String suit, int face) {
        this.suit = suit;
        this.face = face;
    }
    
    public String getSuit() {
        return suit;
    }
    
    public void setSuit(String suit) {
        this.suit = suit;
    }
    
    public int getFace() {
        return face;
    }
    
    public void setFace(int field) {
        this.field = face;
    }
    
    public String toString() {
        return suit + face;
    }
    
}

public class CardDeck {

    private ArrayList<Card> cards;
    
    public CardDeck() {
        cards = new ArrayList<Card>();
    }
    
    public void init() {
        String[] suits = {"S", "H", "D", "C"};
        for (String suit : suits) {
            for (int i = 0; i < 13; i++) {
                Card c = new Card(suit, i + 1);
                cards.add(c);
            }
        }
    }
    
    public Card getCard(int pos) {
        return cards.get(pos);
    }

}
 

UndeadDragon

Super Moderator
Reaction score
447
>GetTriggerUnit-

Shouldn't:
Code:
public String toString() {
        return suit + face;
    }

Be:
Code:
public String toString() {
        return suit + Integer.toString(face);
    }

(I don't know if it's actually needed)
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
It's not.

A string + a number always return a string in java. No need of any kind of convertion. And that's why people don't use Integer.toString much, "" + i returns the number as a string.
 

UndeadDragon

Super Moderator
Reaction score
447
Ok then. It's been a while since I did some Java :p
 

Nenad

~Choco Coronet~ Omnomnom
Reaction score
137
Thanks, i was glad to be on the right track at least.

About the
String suit : suits
in the for loop, what does it do exactly?

I also learned about the rest, we usually never did get/set but rather put it as public.
 

Vestras

Retired
Reaction score
248
Thanks, i was glad to be on the right track at least.

About the in the for loop, what does it do exactly?

I also learned about the rest, we usually never did get/set but rather put it as public.

That is a foreach loop, it is loop that sets the string variable 'suit' to be the current string in the suits collection; it iterates over a collection of something.
 

Nenad

~Choco Coronet~ Omnomnom
Reaction score
137
Gonna post it here, since i'm already openning too many threads (and it's a continuation of my problems xD ).

In any case, i had the code for the person class as such:

Code:
import java.util.ArrayList;

public class Person {
    
    private String name;
    private Person mother;
    private Person father;
    private ArrayList<Person> children;
    
    public Person() {
        children = new ArrayList<Person>();
    }
    
    public boolean isMotherOf(Person potentialChild) {
        if (potentialChild.mother != this)
            return false;
        
        for (Person child : children) {
            if (child == potentialChild)
                return true;
        }
        return false;
    }
    
    public boolean isFatherOf(Person potentialChild) {
        if (potentialChild.father != this)
            return false;
        
        for (Person child : children) {
            if (child == potentialChild)
                return true;
        }
        return false;
    }
    
    public boolean isSiblingOf(Person potentialSibling) {
        return potentialSibling != this &&
               mother.isMotherOf(potentialSibling) &&
               father.isFatherOf(potentialSibling);
    }
}

Written by saw, thank you very much xD

In any case, i'm trying to create a sort of a family tree now, and i'm unsure if i'm doing this right at the moment but:

1. I need to add mother and father to a child. Say that John is the Father and Jane is the mother, and Jake is the son. Is the proper way of adding these attributes as this:

Code:
private Person John;
private Person Jane;
private Person Jack;

 public void createTree()
    {
    	Jack.father = John;
    	Jack.mother = Jane;
    }

Or am i mistaken?

2. I need to print these objects out, and in printing i'm supposed to prove that these objects (people, in this case Jack) has a mother and father. The assignments wording is:
You need to verify that you have created the correct object structure by e.g. printing out all the Person objects in the family. You can do this by making a toString() method in the Person class that prints out the mother, father and children attributes of the object. Then call this method for each member of the family (object).

Now i am unable to get a proper string method with Object.toString(); for some reason, perhaps just wrong syntax. What am i doing wrong here? ><

Thanks for all the help again ^^
 

UndeadDragon

Super Moderator
Reaction score
447
You could refer to the mother and father variables directly, but your variables need to be public, rather than private.

Or you could create functions to get and set the variables.
 

Nenad

~Choco Coronet~ Omnomnom
Reaction score
137
So if i make the mother and father variables public, or add get and set this is the way to do it (e.g the correct code, since that's what i don't know :p )
 

saw792

Is known to say things. That is all.
Reaction score
280
Really what you want is to create a constructor that sets the mother and father, as these are things that can't logically be changed. So something more like:
Code:
public class Person {

    public Person(Person newmother, Person newfather} {
        children = new ArrayList<Person>();
        mother = newmother;
        father = newfather;
    }

    public Person() {
        children = new ArrayList<Person>();
    }

    ...
}

Then, when you are creating your structure:
Code:
private Person John;
private Person Jane;
private Person Jack;

    public void createTree() {
        John = new Person();
        Jane = new Person();
        Jack = new Person(Jane, John);
    }
 

UndeadDragon

Super Moderator
Reaction score
447
Saw's method is better, I didn't think of not being able to change mother and father :p
 

Nenad

~Choco Coronet~ Omnomnom
Reaction score
137
Yes, that was great. Optimized my code a lot ^^

Saw's method is better, I didn't think of not being able to change mother and father
me too :p

Edit: Getting an error with the toString method, i probably messed something up, the code:
Code:
public void ToString(Person name)
    {
    	boolean m = isMotherOf(name);
    	if (m==true)
    	{
    		println("Mother " + name.mother);
    	}
    	else
    	{
    		println("No father known.");
    	}
    	boolean f = isFatherOf(name);
    	if (f==true)
    	{
    		println("Father " + name.father);
    	}
    	else
    	{
    		println("No father known.");
    	}
    	
    }
    public void run ()
    {
    	ToString(Jack);
    }
}

The program extends console, so don't worry about println and such. Also i have no idea how to convert from string to object (Person) variable. >>

Edit: Error is with the calling of isMotherOf method.
Code:
java.lang.NullPointerException
	at x.Person.isMotherOf(Person.java:49) (The main method (Read above))
	at x.Person.ToString(Person.java:78)
	at x.Person.run(Person.java:100)
Rest should be self explanatory
 

GetTriggerUnit-

DogEntrepreneur
Reaction score
129
We need to see the entire code, what you pass to ToString().

And also the way you've done anything it a bit weird. No offense here, you're learning, indeed.
 

Nenad

~Choco Coronet~ Omnomnom
Reaction score
137
And also the way you've done anything it a bit weird. No offense here, you're learning, indeed.

None taken, and indeed i am trying to learn ^^
Code:
import java.util.ArrayList;
import acm.program.*;

public class Person extends ConsoleProgram {
    
    private String name;
    private Person mother;
    private Person father;
    private ArrayList<Person> children;
    private Person John;
    private Person Jane;
    private Person Jack;
    
    public Person (Person newmother, Person newfather) 
	{
            children = new ArrayList<Person>();
            mother = newmother;
            father = newfather;
    }
        
    public void createTree()
    {
    	John= new Person();
    	Jane = new Person();
    	Jack = new Person(Jane, John);
    }
    
    public Person() {
        children = new ArrayList<Person>();
    }
    
    public boolean isMotherOf(Person potentialChild) {
        if (potentialChild.mother != this)
            return false;
        
        for (Person child : children) {
            if (child == potentialChild)
                return true;
        }
        return false;
    }
    
    public boolean isFatherOf(Person potentialChild) {
        if (potentialChild.father != this)
            return false;
        
        for (Person child : children) {
            if (child == potentialChild)
                return true;
        }
        return false;
    }
    
    public boolean isSiblingOf(Person potentialSibling) {
        return potentialSibling != this &&
               mother.isMotherOf(potentialSibling) &&
               father.isFatherOf(potentialSibling);
    }
    
    public void ToString(Person name)
    {
    	boolean m = isMotherOf(name);
    	if (m==true)
    	{
    		println("Mother " + name.mother);
    	}
    	else
    	{
    		println("No father known.");
    	}
    	boolean f = isFatherOf(name);
    	if (f==true)
    	{
    		println("Father " + name.father);
    	}
    	else
    	{
    		println("No father known.");
    	}
    	
    }
    public void run ()
    {
    	boolean b = isMotherOf(Jack);
    	System.out.println(b);
    }
}

Here is the entire code so far, so i probably did not do something correct. I would like to know how to test the methods (since that is a part of the assignment it seems). I can use a string but i have no clue how to convert the string into the object or person variable. I need to test all the methods for given names: Say i test isMotherOf, then i need a method (void) that will test and give a positive result back. However, currently i get a java.applet error when i try to run the method isMotherOf. I also need to know how to get the mother object if the child has a mother. In other words how to get the mothers name in string when i type in the name of a child.
 

Nenad

~Choco Coronet~ Omnomnom
Reaction score
137
Code:
import java.util.ArrayList;
import acm.program.*;

public class Person extends ConsoleProgram {
    
    private String name;
    private Person mother;
    private Person father;
    private ArrayList<Person> children;
    private Person John;
    private Person Jane;
    private Person Jack;
    
    public Person (Person newmother, Person newfather) 
	{
            children = new ArrayList<Person>();
            mother = newmother;
            father = newfather;
    }
        
    public void createTree()
    {
    	John = new Person();
    	Jane = new Person();
    	Jack = new Person(Jane, John);
    }
    
    public Person() {
        children = new ArrayList<Person>();
    }
    
    public boolean isMotherOf(Person potentialChild) {
        if (potentialChild.mother != this)
            return false;
        
        for (Person child : children) {
            if (child == potentialChild)
                return true;
        }
        return false;
    }
    
    public boolean isFatherOf(Person potentialChild) {
        if (potentialChild.father != this)
            return false;
        
        for (Person child : children) {
            if (child == potentialChild)
                return true;
        }
        return false;
    }
    
    public boolean isSiblingOf(Person potentialSibling) {
        return potentialSibling != this &&
               mother.isMotherOf(potentialSibling) &&
               father.isFatherOf(potentialSibling);
    }
    
    public void ToString(Person name)
    {
    	boolean m = isMotherOf(name);
    	if (m==true)
    	{
    		println("Mother " + name.mother);
    	}
    	else
    	{
    		println("No mother known.");
    	}
    	boolean f = isFatherOf(name);
    	if (f==true)
    	{
    		println("Father " + name.father);
    	}
    	else
    	{
    		println("No father known.");
    	}
    	
    }
    public void run ()
    {
    	createTree();
    	ToString(Jack);
    }
}

Now it works, but returns no mother, no father found. How do i get the names of the mother and father from the objects?
 

saw792

Is known to say things. That is all.
Reaction score
280
I'd just like to take this opportunity to clarify something for you. The toString() method in any class is designed to create a string representation of (an instance of) an entire class. Sometimes it's difficult to think immediately what that representation should be, so here are a few examples:

1. String class: A string is just a container for some characters which can already be printed, so the best representation of a String instance is the String data it contains.

2. Integer class: The best representation of an integer in a string would be the integer itself, in string form. So if the integer stored inside the Integer instance is a 3, the string form would be "3".

3. A Circle class storing x position, y position and radius: The best string representation of an instance of Circle is a string containing these three pieces of data. See example below.

By adding a toString() method into your class you are defining a format for presenting the data contained within it. The natural way to do this for your Person class (which contains only family information) is to present this family information in a readable way.

Circle Example:
Code:
public class Circle {

        private double rad;
	private double x;
	private double y;
	
	public Circle(double xpos, double ypos, double radius) {
	    x = xpos;
            y = ypos;
            rad = radius;
	}
	
	public String toString() {
	    return "Radius: " + rad + "/nX Position: " + x + "/nY Position" + y;
	}

}

For the Person class you only need to return a string containing the important information that is asked for. No println() or anything like that. Error checking happens somewhere else, perhaps comparing outputs of the toString() method of difference instances of Person (i.e. compare Jack.toString() and Jane.toString() to see if one is the other's parents, and if it is consistent in both instances).
 

UndeadDragon

Super Moderator
Reaction score
447
Code:
public String toString() {
       return this.name;
}

+ I would make the constructor take the person's name as a parameter.

You would then use:

Person test = new Person("Bob", mother, father);

String personName = test.toString();
 
General chit-chat
Help Users
  • No one is chatting at the moment.

      The Helper Discord

      Staff online

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top