Search code examples
javaif-statementskip

How to skip an else statement a certain number of times, then start again


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.


Solution

  • 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.