首页 > 解决方案 > 空行从哪里来?如何删除它?- 爪哇

问题描述

我想打印出没有重复单词的字符串。第一个 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(); 
}

标签: java

解决方案


当您为行键入 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 个元素组成的数组,第一个元素是空字符串""


推荐阅读