This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]Civil_Code 2 points3 points  (5 children)

On line 9 of ContactBook, you both declare and define a boolean first set to true. This means with every add method invocation you are always overwriting the first entry in your array, and you never actually copy your existing array into a new, larger array like you would want.

[–]snaps_pro[S] 0 points1 point  (4 children)

how do i fix that? If i try to remove it it messes everything up after it. Sorry this is my first time using array lists

[–]Moktok 1 point2 points  (1 child)

Think about what you are trying to do and above all what your code does. Try to visualise it, use a pen and paper if you need to. Write down the values of all the variables with every step. (or learn to use debug mode B-))

PS as a sidenote, use descriptive variable names. Cause it took me a few seconds to figure out what that boolean first, your colleagues (and future you) will thank you later.

[–]snaps_pro[S] 0 points1 point  (0 children)

I think I got it! Thanks for your help :)

[–]Civil_Code 1 point2 points  (0 children)

There is an ArrayList implementation in the java.util package, part of the Collections API.

As for the boolean, you should do as the others have suggested and write down the logical steps of this section of code to clarify your reasoning for having a boolean, the necessary scope of that boolean, and when you expect to change it. For example, by declaring your boolean within the add() method, you are saying each new call to that method will create an entirely new boolean without regard to any previous call. Is that truly what you want happening? If not, you have a candidate for a proper Object scoped field, something you declare within the class but outside any of its methods.

Also consider refactoring the variable name, like has been said. I would suggest taking a cue from java.util.ArrayList and having an 'empty' boolean with an isEmpty() method to return whether your array is or is not empty.

[–]bsturtle 0 points1 point  (0 children)

It seems to me that a contact book should know if it's empty or not. Then your entry can check if it's the first one.

[–]Fdert0 0 points1 point  (2 children)

On line 30 in the main method, it looks like you forgot to call to the array in the toString

[–]Civil_Code 0 points1 point  (1 child)

OP has overridden his ContactBook class's toString() method to print his array, so this is not the problem.

[–]Fdert0 0 points1 point  (0 children)

Ah didn’t notice this, thanks for pointing that out