The moose likes Beginning Java and the fly likes Array probelm Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array probelm" Watch "Array probelm" New topic

Array probelm

Jj Jiang

Joined: Jan 22, 2013
Posts: 1

I'm basically stuck on how you create a new acquaintance array with one extra element and the steps you go from there to finish. Our teacher wants us to just use arrays and make a loop to create a new bigger Array for each addiional element. Can someone help?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15080

Welcome to the Ranch.

Arrays in Java have a fixed size. So you cannot make an array longer or shorter once it has been created - what you should do instead, is create a new array of the right size, and then copy the values of the old array into the new array. The comments in your code already explain the steps to do that.

If this wasn't a homework exercise, you'd use a class such as an ArrayList instead of using arrays - because an ArrayList can grow and shrink.

In line 3 of your code you are creating an array of length 0. You cannot put anything into that array, because its length is 0 - there's no space for any elements. In line 20 you're trying to assign something to the first entry in the array (acqs[0]). That will result in an ArrayIndexOutOfBoundsException - an array of length 0 has no elements at all, even index 0 is invalid.

Some hints:

You create a new array just like you did in line 3: new Acqaintance[...] where ... is the new length that you want the array to have.

You can get the length of an array with .length: so acqs.length is the length of the acqs array.

You can use a for-loop to copy elements from the old to the new array.

See Arrays and The for Statement in Oracle's Java tutorials.

Good luck!

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Array probelm
It's not a secret anymore!