Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: toString not printing everything in the Array which is in a seperate class

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default toString not printing everything in the Array which is in a seperate class

    Hi all,
    Im having huge problems trying to get a toString method in one class to print everything in the array in another class. It will be ok if i just add a guard or a center, but as soon as i add a guard, then add a center it only prints the last entry. Its like it isn't storing everything in the array. It stores one entry (or even group of entries if i chose to enter more than one player) but as soon as i want to add to it, it gets written over. Im very new to Java so i hope i have made sense (and importantly added everything required to find a resolution to this problem - i have spent hours trying to sort it to no avail).

    In total there are 4 classes, basketballPlayer is where the toString is located and playerStats is where im asking the user to input the info and 'store' it in an array.
    Hope i have included everything. Im sure there are other issues but im really after a solution to this at the moment.

    Thanks in advance, this is driving my crazy.

    import java.util.*;
    public class basketballPlayer
    {
        Scanner scan = new Scanner (System.in);
        String name;
        int age = 0;
        int positionRanking = 0;
        int drafted = 0;
     
        float height = 0;
     
        public basketballPlayer (String name, int age, int positionRanking, int drafted, float height)
        {
            this.name = name;
            this.age = age;
            this.positionRanking = positionRanking;
            this.drafted = drafted;
            this.height = height;
        }
     
        public void setName (String entName)
        {
            name = entName;
        }
     
        public void setAge (int entAge)
        {
            age = entAge;
        }
     
        public void setPositionRanking (int entPositionRanking)
        {
            positionRanking = entPositionRanking;
        }
     
        public void setDrafted (int entDrafted)
        {
            drafted = entDrafted;
        }
     
        public void setHeight (float entHeight)
        {
            height = entHeight;
        }
     
        public String getName ()
        {
            return name;
        }
     
        public int getAge ()
        {
            return age;
        }
     
        public int getPositionRanking ()
        {
            return positionRanking;
        }
     
        public int getDrafted ()
        {
            return drafted;
        }
     
        public float getHeight ()
        {
            return height;
        }
     
        public String toString (int threePointers, int steals, int totalSeasonPointsG, int blocks, int dunks, int totalSeasonPointsC)
        {
        	String result = "";
        	result += "Name: "+name+"\tAge: "+age+"\tHeight: "+height+"\tDrafted: "+drafted+"\tPosition Ranked: "+positionRanking;
        	if(blocks > 0)
        	{
        		result += "\nBlocks: "+blocks+"\nDunks: "+dunks+"\nTotal Season Points: "+totalSeasonPointsC;
        	}
        	else if (threePointers > 0)
        	{
        		result += "\nThree Pointers: "+threePointers+"\nSteals: "+steals+"\nTotal Season Points: "+totalSeasonPointsG;
        	} 
     
        	return result;
        }
     
    }

    Here is the playerStats class

     
    import java.util.*;
     
    public class playerStats
    {
        Scanner scan = new Scanner (System.in);
        String name;
        int ex = 0;
        int choice;
        int num;
        int update;
        int NULL_SIZE = 0;
        basketballPlayer[] players = new basketballPlayer[NULL_SIZE];  
     
        public void userInput()
        {
            String teamName;
     
            System.out.println ("Enter a team name: ");
            teamName = scan.nextLine();
            System.out.println ("");
     
            while (ex != 1)
            {
                System.out.println (" SEASON STATS ");
                System.out.println ("For the team: " + teamName);
                System.out.println ("");
                System.out.println ("1. Add a point or shooting guard");
                System.out.println ("2. Add a center");
                System.out.println ("3. Show players statistics");
                System.out.println ("4. Update a players statistics");
                System.out.println ("5. Exit");
                choice = scan.nextInt();
                scan.nextLine();
     
                switch(choice)
                {
                    case 1: 
                    {
                        addGuard();      break;
                    }
                    case 2:
                    {
                        addCenter();     break;
                    }
                    case 3:
                    {
                        entireList();    break;
                    }
                    case 4: 
                    {
                        updateStats();   break;
                    }
                    case 5:
                    {
                        ex = 1;          break;
                    }
                }
            }
        }
     
        public void addGuard()
        {
            System.out.println ("Please indicate how many players (Guards) you would like to add: ");
            num = scan.nextInt();
            scan.nextLine();
            if (num > players.length)
            {
                incSize(num);
            }
            for (int i = 0; i < num; i ++)
            {
                players[i] = new positionGuard (entName(),entAge(), entHeight(), entPositionRanking(), entDrafted(), entThreePointers(), entSteals(), entTotalSeasonPointsG());
            }
        }
     
        public void addCenter()
        {
            System.out.println ("Please indicate how many players (Centers) you would like to add: ");
            num = scan.nextInt();
            scan.nextLine();
            if (num > players.length)
            {
                incSize(num);
            }
            for (int i = 0; i < num; i ++)
            {
                players[i] = new positionCenter (entName(),entAge(), entHeight(), entPositionRanking(), entDrafted(), entBlocks(), entDunks(), entTotalSeasonPointsC());
            }
        }
     
        public void entireList()         //////////////////////// This is doing its job (i think) but the array keeps getting overwritten when a new entry is added: AddCenter or AddGuard
        {
     
            for (int i = 0; i < players.length; i++)
            {
            System.out.println (players[i].toString());
            }
        }
     
        public void updateStats()
        {
            int option;
            System.out.println ("Please select from the following options: ");
            System.out.println ("1. Update a guards statistics: ");
            System.out.println ("2. Update a centers statistics: ");
            option = scan.nextInt();
            scan.nextLine();
     
            if (option == 1)
            {
                System.out.println ("What is this players name?");
                name = scan.nextLine();
     
                for (int i = 0; i < players.length; i ++)
                {
                    if (players[i].getName().equals(name))
                    { 
                        updateAge(i);
                        updateHeight(i);
                        updatePositionRanking(i);
                        updateThreePointers(i); 
                        updateSteals(i);
                        updateTotalSeasonPointsG(i);;
                    }
                    else
                    {
                        System.out.println ("Players name is spelt incorrectly or doesn't exist");
                    }
                }
            }
     
            if (option == 2)
            {
                System.out.println ("What is this players name: ");
                name = scan.nextLine();
     
                for (int i = 0; i < players.length; i ++)
                {
                    if (players[i].getName().equals(name))
                    { 
                        updateAge(i);
                        updateHeight(i);
                        updatePositionRanking(i);
                        updateBlocks(i); 
                        updateDunks(i);
                        updateTotalSeasonPointsC(i);
                    }
                    else
                    {
                        System.out.println ("Players name is spelt incorrectly or doesn't exist");
                    }
                }
            }
        }
     
        public String entName()
        {
            String name;
            System.out.println ("The players name is: ");
            name = scan.nextLine();
            return name;
        }
     
        public int entAge()
        {
            int age;
            System.out.println ("The players age is: ");
            age = scan.nextInt();
            scan.nextLine();
            return age; 
        }
     
        public float entHeight()
        {
            float height;
            System.out.println ("The players height is: ");
            height = scan.nextFloat();
            scan.nextLine();
            return height;
        }
     
        public int entPositionRanking()
        {
            int positionRanking;
            System.out.println ("The players position ranking is: ");
            positionRanking = scan.nextInt();
            scan.nextLine();
            return positionRanking;
        }
     
        public int entDrafted()
        {
            int drafted;
            System.out.println ("The player was drafted in the year: ");
            drafted = scan.nextInt();
            scan.nextLine();
            return drafted;
        }
     
        public int entThreePointers()
        {
            int threePointers;
            System.out.println ("How many three pointers has the player successfully shot: ");
            threePointers = scan.nextInt();
            scan.nextLine();
            return threePointers;
        }
     
        public int entSteals()
        {
            int steals;
            System.out.println ("How many steals has the player successfully completed: ");
            steals = scan.nextInt();
            scan.nextLine();
            return steals;
        }
     
        public int entTotalSeasonPointsG()
        {
            int totalSeasonPointsG;
            System.out.println ("How many points has the player accumulated this season: ");
            totalSeasonPointsG= scan.nextInt();
            scan.nextLine();
            return totalSeasonPointsG;
        }
     
        public int entTotalSeasonPointsC()
        {
            int totalSeasonPointsC;
            System.out.println ("How many points has the player accumulated this season: ");
            totalSeasonPointsC= scan.nextInt();
            scan.nextLine();
            return totalSeasonPointsC;
        }
     
        public int entDunks()
        {
            int dunks;
            System.out.println ("How many dunks has the player achieved: ");
            dunks = scan.nextInt();
            scan.nextLine();
            return dunks;
        }
     
        public int entBlocks()
        {
            int blocks;
            System.out.println ("How many blocks has the player achieved: ");
            blocks = scan.nextInt();
            scan.nextLine();
            return blocks;
        }
     
        public void updateAge(int i)
        {
            int updateA;
            System.out.println ("Enter a new age, or enter '0' to leave it at the current value");
            updateA = scan.nextInt();
            scan.nextLine();
     
            if (updateA > 0)
            {
                players[i].setAge(updateA);
            }
        }
     
        public void updateHeight(int i)
        {
            int updateB;
            System.out.println ("Enter a new height, or enter '0' to leave it at the current value");
            updateB = scan.nextInt();
            scan.nextLine();
     
            if (updateB > 0)
            {
                players[i].setHeight(updateB);
            }
        }
     
        public void updatePositionRanking(int i)
        {
            int updateC;
            System.out.println ("Enter a new position rank, or enter '0' to leave it at the current value");
            updateC = scan.nextInt();
            scan.nextLine();
     
            if (updateC > 0)
            {
                players[i].setPositionRanking(updateC);
            }
        }
     
        public void updateThreePointers(int i)
        {
            basketballPlayer bballGuard = players[i];
            positionGuard guard = (positionGuard) bballGuard;
     
            int updateD;
            System.out.println ("Enter a new value, or enter '0' to leave it at the current value");
            updateD = scan.nextInt();
            scan.nextLine();
     
            if (updateD > 0)
            {
                guard.setThreePointers(updateD);
            }
            else
            {
                System.out.println ("Incorrect value entered, must be greater than '0' ");
            }
        }
     
        public void updateSteals(int i)
        {
            basketballPlayer bballGuard = players[i];
            positionGuard guard = (positionGuard) bballGuard;
     
            int updateE;
            System.out.println ("Enter a new value: ");
            updateE = scan.nextInt();
            scan.nextLine();
     
            if (updateE > 0)
            {
                guard.setSteals(updateE);
            }
            else
            {
            System.out.println ("Incorrect value entered, must be greater than '0' ");
            }
        }
     
        public void updateBlocks(int i)
        {
            basketballPlayer bballCenter = players[i];
            positionCenter center = (positionCenter) bballCenter;
     
            int updateF;
            System.out.println ("Enter a new value: ");
            updateF = scan.nextInt();
            scan.nextLine();
     
            if (updateF > 0)
            {
                center.setBlocks(updateF);
            }
            else
            {
            System.out.println ("Incorrect value entered, must be greater than '0' ");
            }
        }
     
        public void updateDunks(int i)
        {
            basketballPlayer bballCenter = players[i];
            positionCenter center = (positionCenter) bballCenter;
     
            int updateG;
            System.out.println ("Enter a new value: ");
            updateG = scan.nextInt();
            scan.nextLine();
     
            if (updateG > 0)
            {
                center.setDunks(updateG);
            }
            else
            {
            System.out.println ("Incorrect value entered, must be greater than '0' ");
            }
        }
     
        public void updateTotalSeasonPointsG(int i)
        {
            basketballPlayer bballGuard = players[i];
            positionGuard guard = (positionGuard) bballGuard;
     
            int updateH;
            System.out.println ("Enter a new value: ");
            updateH = scan.nextInt();
            scan.nextLine();
     
            if (updateH > 0)
            {
                guard.setTotalSeasonPointsG(updateH);
            }
            else
            {
            System.out.println ("Incorrect value entered, must be greater than '0' ");
            }
        }
     
        public void updateTotalSeasonPointsC(int i)
        {
            basketballPlayer bballCenter = players[i];
            positionCenter center = (positionCenter) bballCenter;
     
            int updateK;
            System.out.println ("Enter a new value: ");
            updateK = scan.nextInt();
            scan.nextLine();
     
            if (updateK > 0)
            {
                center.setTotalSeasonPointsC(updateK);
            }
            else
            {
            System.out.println ("Incorrect value entered, must be greater than '0' ");
            }
        }
     
        public void setName(String upName)
        {
            name = upName;
        }
     
        public String getName()
        {
            return name;
        }
     
        public static void main (String [] args)
        {
            playerStats stats = new playerStats();
            stats.userInput();
        } 
     
        public void incSize (int inc)
        {
            int size = players.length;
            size = size + inc;
     
            basketballPlayer [] temp = new basketballPlayer [size];
            for (int i = 0; i < players.length; i ++)
            {
                temp[i] = players[i];
     
            }
            players = temp;
        }   
     }
    Last edited by taz_1891; September 29th, 2012 at 08:28 PM. Reason: its a mess, want to add the code properly


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Please edit your post above and add [code=java] [/code] tags around your code (just as I've shown). This will help make your code retain its formatting and be more readable.

    As for your problem, note that the toString method should take no parameters. That is, it should look like:

    public String toString () {
       // .... your code here ...
    }

    not,
    public String toString (int threePointers, int steals, int totalSeasonPointsG, int blocks, double priceOfPeanutsInChina) {
      // ...
    }

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Even if its getting those parameters from the other two classes?
    I have two other classes (positionCenter and positionGuard) which stores that info.

    P.S Sorry about the original effort. As soon as i sore it i knew there was an issue.

    cheers

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Quote Originally Posted by taz_1891 View Post
    Even if its getting those parameters from the other two classes?
    I have two other classes (positionCenter and positionGuard) which stores that info.
    Yes, even if it is getting those parameters from other classes. the toString() method is a special method of the base class of all classes, Object, and it must have a method signature that *exactly* matches that of its parent class. In fact it's always a good idea to precede this method with the @Override annotation to be sure that you're configuring it right.

    The method is supposed to display the state of the current object, and so parameters should never be necessary for this method (even if it were possible that they could be used).

  5. #5
    Junior Member
    Join Date
    Sep 2012
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Ah ok (i think i understand).

    So will that is definitely one issue (thanks) but it wouldn't relate to the array problem would it. The fact that everything gets written over when a new entry is added

  6. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Quote Originally Posted by taz_1891 View Post
    So will that is definitely one issue (thanks) but it wouldn't relate to the array problem would it. The fact that everything gets written over when a new entry is added
    I'm not sure as you've yet to describe your problem in detail. Please do so.

  7. #7
    Junior Member
    Join Date
    Sep 2012
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Sorry.

    The problem is when i add a player (addCenter or addGuard), it suppose to store the information the user inputs into an array. Then at the menu, when they select option 3 (Show players statistics), it suppose to go to the toString method in the other class and print the players details. The point is that the user can input as many players as they want (guards or centers or both) and all their details. Again, when the user goes back to the main menu, it should print ALL players in the array and their details. The more players you add the larger the print should be.

    Whats happening is that when a user adds a guard and their details, then adds a center and their details (or visa versa) - when the user selects option 3 (Show players statistics), it only shows the last entry. You could enter 10 guards and it will print them all out but as soon as you select to add another player (guard or center), it again seems to overwrite the original 10 guards that you had entered and only print out the current entry.

    Hope that makes sense.

    I will add the other code just so you have the whole picture (hopefully).

     
    public class positionGuard extends basketballPlayer
    {
        int threePointers;
        int steals;
        int totalSeasonPointsG;
     
        public positionGuard (String name, int age, float height, int positionRanking, int drafted, int threePointers, int steals, int totalSeasonPointsG)
        {
            super (name, age, positionRanking, drafted, height);
            this.threePointers = threePointers;
            this.steals = steals;
            this.totalSeasonPointsG = totalSeasonPointsG;
        }
     
        public void setThreePointers(int entThreePointers)
        {
            threePointers = entThreePointers;
        }
     
        public void setSteals (int entSteals)
        {
            steals = entSteals;
        }
     
        public void setTotalSeasonPointsG(int entTotalSeasonPointsG)
        {
            totalSeasonPointsG = entTotalSeasonPointsG;
        }
     
         public int getThreePointers()
        {
            return threePointers;
        }
     
         public int getSteals()
        {
            return steals;
        }
     
        public int getTotalSeasonPointsG()
        {
            return totalSeasonPointsG;
        }
     
     
        public String toString()
        {
            return super.toString(threePointers, steals, totalSeasonPointsG, 0, 0, 0);
        }
    }


     
    public class positionCenter extends basketballPlayer
    {
        int blocks;
        int dunks;
        int totalSeasonPointsC;
     
        public positionCenter (String name, int age, float height, int positionRanking, int drafted,  int blocks, int dunks, int totalSeasonPointsC)
        {
            super (name, age, positionRanking, drafted, height);
            this.blocks = blocks;
            this.dunks = dunks;
            this.totalSeasonPointsC = totalSeasonPointsC;
        }
     
        public void setBlocks(int entBlocks)
        {
            blocks = entBlocks;
        }
     
        public void setDunks (int entDunks)
        {
            dunks = entDunks;
        }
     
        public void setTotalSeasonPointsC(int entTotalSeasonPointsC)
        {
            totalSeasonPointsC = entTotalSeasonPointsC;
        }
     
         public int getBlocks()
        {
            return blocks;
        }
     
         public int getDunks()
        {
            return dunks;
        }
     
        public int getTotalSeasonPointsC()
        {
            return totalSeasonPointsC;
        }
     
        public String toString()
        {
            return super.toString(0, 0, 0, blocks, dunks, totalSeasonPointsC);
        }
    }

  8. #8
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    OK that makes more sense. Let's look at your addguard() method, OK?

        public void addGuard()
        {
            System.out.println ("Please indicate how many players (Guards) you would like to add: ");
            num = scan.nextInt();
            scan.nextLine();
            if (num > players.length)
            {
                incSize(num);
            }
            for (int i = 0; i < num; i ++)
            {
                players[i] = new positionGuard (entName(),entAge(), entHeight(), entPositionRanking(), entDrafted(), entThreePointers(), entSteals(), entTotalSeasonPointsG());
            }
        }

    The key code is actually here:
            for (int i = 0; i < num; i ++)
            {
                players[i] = new positionGuard (entName(),entAge(), entHeight(), entPositionRanking(), entDrafted(), entThreePointers(), entSteals(), entTotalSeasonPointsG());
            }

    Assume that there are already 10 Player objects in the players array and you're adding the 11th. What do you think that this for loop will do to the data held in players[0] to players[9], data that you've already entered into the array?

  9. The Following User Says Thank You to curmudgeon For This Useful Post:

    taz_1891 (September 30th, 2012)

  10. #9
    Junior Member
    Join Date
    Sep 2012
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Ok, so num in the for loop should actually be players.length (the size of the array). But i feel it will still start from the beginning and write over everything every time i 'add' a player.

    So will i need to start the loop at the beginning of the last entry (something like players.length - num , and end it at i < players.length) ??

    By the way, thanks for you help so far curmudgeon. Much appreciated.
    Last edited by taz_1891; September 30th, 2012 at 01:36 AM.

  11. #10
    Junior Member
    Join Date
    Sep 2012
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    Ok got it !!

    if (num > players.length)
            {
                incSize(num);

    Was also killing me. It obviously wasn't doing its job correctly.... well it was, my attempt at coding was what was inadequate.
    It wasn't purely increasing the array as a new entry was coming in.

    All fixed and seems working correctly for now.

    Thanks again for your help!
    I have this here cause im new and don't want to forget:[ highlight=Java]//code goes here...[/highlight] tags when posting code

  12. #11
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: toString not printing everything in the Array which is in a seperate class

    You're welcome!

Similar Threads

  1. WindowBuilder - How do I open a seperate class window by a button?
    By tizen in forum Java Theory & Questions
    Replies: 1
    Last Post: July 29th, 2012, 05:11 PM
  2. Calling a print method from another class (printing array)
    By Kaldanis in forum Object Oriented Programming
    Replies: 7
    Last Post: November 25th, 2011, 01:32 PM
  3. Replies: 1
    Last Post: September 28th, 2011, 07:29 AM
  4. Switching between frames from a seperate class
    By kurt-hardy in forum AWT / Java Swing
    Replies: 4
    Last Post: February 14th, 2011, 04:19 AM
  5. [SOLVED] Using class implicit toString() for array index
    By Quetzalma in forum Java Theory & Questions
    Replies: 2
    Last Post: February 3rd, 2010, 05:04 PM