我想打印出没有重复单词的字符串。第一个int决定我有多少个字符串,然后是带有重复项的字符串。但是在我的输出中,我在第一行有一个空行,我想知道如何摆脱这第一个空行? 感谢您的时间和帮助!
Input Example:
3
Goodbye bye bye world world world
Sam went went to to to his business
Reya is is the the best player in eye eye game
Output:
*empty line*
Goodbye bye world
Sam went to his business
Reya is the best player in eye game
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int lines= sc.nextInt()+1;
String [] str= new String[lines];
for(int i=0;i<lines;i++) {
str[i]=sc.nextLine();
}
for(int i=0;i<lines;i++) {
String temp= str[i];
String[] strWords = temp.split("\\s+");
LinkedHashSet<String> hstr = new LinkedHashSet<String> ();
for(int j=0;j<strWords.length;j++) {
hstr.add(strWords[j]);
}
String[] strArr = new String[hstr.size()];
hstr.toArray(strArr);
for(int k=0;k<hstr.size();k++) {
System.out.printf("%s", strArr[k] + " ");
}
System.out.println();
}
sc.close();
}
答案 0 :(得分:0)
当您在行中键入3时,此代码:
int lines= sc.nextInt()+1; // why + 1?
String [] str= new String[lines];
for(int i=0;i<lines;i++) {
str[i]=sc.nextLine();
}
创建一个由4个元素组成的数组,第一个元素为空字符串""