-5

I have a question asking to read indexes and check if its empty and if it is and its at a position greater than or equal to 67(starting from 0), I must print out the element located at index i-67. The problem I'm having I believe is checking if an index contains anything

  for(int i = 0; i <= s.size()-1; i++){
    if(s.get(i) == null && i >= 67)
      w.println(s.get(i-67));
  }

I read elsewhere that maybe a hashtable would be better for doing this but I for the life of me can't understand why.

halfer
  • 19,824
  • 17
  • 99
  • 186
Tdlk
  • 1
  • 1
  • 2
  • runtime error, compiler error, wrong data output, please specify. – Murillio4 Oct 01 '16 at 21:21
  • 1
    `i <= s.size()-1;` really? – FredK Oct 01 '16 at 21:22
  • Sorry, wrong data output was my issue, as it would never recognize if an index was empty. @FredK yes what about it? Anyways I found a solution to my question, apparently I was using the wrong data structure for the problem. Also if anyone cares to know the reason it wouldn't pick up was because Strings are not a primitive data type so you'd need to do if(s.get(i).equals(null)) to get the correct result! Thanks everyone! – Tdlk Oct 01 '16 at 22:49

1 Answers1

1

Using if(s.get(i) == null) doesn't work, and the method get() throws an exception instead of returning null.

You need to catch the exception, use this:

try {
    s.get(i);
} catch (IndexOutOfBoundsException e) {
    s.add(i, new Object());//Add something to fill this position.
}

If the Arraylist in the i position is null (empty), the code catch the exception and you can add something to fill that position. You didn't specify what type is your Arraylist.

TimeToCode
  • 901
  • 2
  • 16
  • 34