Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Find all indexes of target valuein an array Java

 
ryan wellhouser
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone.
I have an assignment which requires me to create a method that will search through an array for a target value and print all the indexes it occurs at in a new array. The parts im having the most trouble with is creating a new array to hold the values of the indexes that are found. Any ideas? Thanks.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The parts im having the most trouble with is creating a new array to hold the values of the indexes that are found.

Are you required to use an array, or can you use a java.lang.List instead ?
 
ryan wellhouser
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately you are required to create a separate array.
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you really have to create a separate array? If the assignment is just to print the indexes that match, can you just iterate through the array and print out an index as you find equal values? Or you can build a String that holds the output, and print the String at the end of the method.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you don't know what size the array is going to be, it will be annoying. You can still make an array whose size if as big as the input array. Otherwise, I think you'll have to loop twice, once to get the number of matching indexes, and another one to store the indexes. Can you figure this out ?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic