• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Array probelm

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
reply
    Bookmark Topic Watch Topic
  • New Topic