Vswe's Summer Courses | You're not logged in. Sign up or log in | Server time: | Donate
One can now see other persons' badge hunts. Simply head over to their profiles to access them.

Go back to course page

Thinking with objects

Object orientated programming in Java

Derping on Assignment

  • 2013-07-04 14:58:21
    I've just started working on the assignment, but I keep running into this problem when I am using for loops. It either adds something into an array twice or prints it out twice, instead of just doing it once. I know I have derped, but I have no clue what I have done wrong. Can anyone see the problem?

    public static void printPlayers(){
            for(int i = 1; i < 3; i++){
                if(players[i] != null){
                    System.out.println(players[i].getName());
                }
            }
        }

    Output:
    Bot 1
    Bot 1

    It should only print that out once.
  • 2013-07-04 15:06:57
    Fixed it, I added a break into the method which added the players into the array.
  • 2013-07-04 15:09:41
    Not sure why it prints out the same bot twice (maybe you added it twice to the array? did you give some bots the same name?), but there is a problem i see: Arrays always start with index 0.

    So, to print all players in the player array, you would use:
    for (int i = 0; i < players.length; i++) {
    if (players[i] != null) {
    System.out.println(players[i].getName());
    }
    }

    Hope, this helps you a little bit. If not, could you show how your array players is defined and initialized?
  • 2013-07-04 15:10:35
    Ah ok, so my reply was to late ... anyway, you might still want to check your array indices starting with 0 :)
  • 2013-07-04 15:18:01
    Yh, it was at 1 for debugging. Now onto the rest of the program.
  • 2013-07-05 11:37:01
    Also, you might want to change the condition i < 3 to something like i < myArray.length. This makes the program much more expandable, because you can just change the length of the players array without having to change anything else.
  • Log in or sign up to reply to this thread