Forums Register Login

Array probelm

+Pie Number of slices to send: Send

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?
+Pie Number of slices to send: Send
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!
The two armies met. But instead of battle, they decided to eat some pie and contemplate this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 698 times.
Similar Threads
Populate Array of type Double from text file
2d array issues.
Tokens into array, datatype??
scoured the net for reusable ftp program but having problems
help me please??
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 08:50:00.