0

I have a list of names in an array, and there is some redundancy in it. I was able to get only unique names to print, but I need a way to print the first line, skip the printing however many times there was a redundancy, then continue printing the next name (all redundant instances were always next to eachother). Here is what I have for that part so far:

int x = 1;
int skipCount = 0;
while (x<i){
  if (titles[x].length() == titles[x-1].length()){
   //do nothing 
    skipCount++;
  }
  else{
    System.out.printf("%s\n", titles[x]);
  }
  x++;
}

So basically, how would I go about skipping the else statement 'skipCount' times, then have it start again? I haven't found much about this and am relatively new to java.

dra
  • 3
  • 1
  • 4
    I don't quite understand your question. Could you give an example? titles + expected output? – Karoly Horvath Aug 20 '12 at 21:50
  • You don't seem to have declared `i`? – ChrisW Aug 20 '12 at 21:50
  • 1
    @dra why are you comparing the titles by `length`? – obataku Aug 20 '12 at 21:50
  • Can you use a `Set`? That would remove duplicates for you upon insertion. – Dan W Aug 20 '12 at 21:50
  • 1
    @ChrisW I think you can infer `i = titles.length` – obataku Aug 20 '12 at 21:50
  • You can't "skip" an `else` statement if the previous `if` evaluated to false. Perhaps you need to rework some of the logic? Just to clarify you are trying to simply stop from printing the same string twice? – Chris Dargis Aug 20 '12 at 21:52
  • @KarolyHorvath Lets see if this makes sense: I have a bunch of html files that I took the block out of. Many of these htmls have the same title, so I am trying to make a program to group them by title. – dra Aug 20 '12 at 21:58

1 Answers1

2

Why not just use a Set? ;-)

final Set<String> set = new HashSet<>(Arrays.asList(titles));
for (final String title : set) {
  /* title is unique */
  System.out.println(title);
}

Some of the changes include using println rather than printf("%s\n", ...), which is just clearer, and using an enhanced for loop, instead of manually tracking the position in the array in a loop.

To be honest, you might consider using a Set<String> in place of String[] for titles in the first place.

obataku
  • 29,212
  • 3
  • 44
  • 57
  • Thanks for the answer. I couldn't get what you posted to work, but it definitely got me going in the right direction. – dra Aug 21 '12 at 13:35