0

我有一个数组中的名称列表,其中有一些冗余。我只能打印唯一的名称,但我需要一种方法来打印第一行,跳过打印但多次出现冗余,然后继续打印下一个名称(所有冗余实例总是彼此相邻)。到目前为止,这是我对该部分的内容:

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++;
}

所以基本上,我将如何跳过 else 语句“skipCount”次,然后让它重新开始?我对此并没有太多了解,并且对 java 比较陌生。

4

1 回答 1

2

为什么不只使用 a Set?;-)

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

一些更改包括使用println而不是printf("%s\n", ...)更清晰,以及使用增强的for循环,而不是手动跟踪循环中数组中的位置。

老实说,您可能会首先考虑使用 aSet<String>代替String[]for titles

于 2012-08-20T21:52:23.793 回答