java - 空行从哪里来?如何删除它?- 爪哇
问题描述
我想打印出没有重复单词的字符串。第一个 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();
}
解决方案
当您为行键入 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 个元素组成的数组,第一个元素是空字符串""
推荐阅读
- python - 使用 MaskRcnn 从 model.detect() 之后的图像中获取预测掩码的 x,y 坐标
- oop - Dart 子类型和方法参数
- vue-router - 允许路由器防护中的 2 个组件
- docker - 使用动态 docker 代理时如何构建 docker 映像?
- java - 如何确保正确封装字段?
- c++ - 为什么我在数组中输入了一定数量的字母后程序就结束了?
- android - 如何在颤动中仅对一个小部件使用 setState 方法?
- vb.net - 为什么我的 pascals_triangle 数组没有充当二维列表,因此给了我太多参数错误?
- google-analytics - Google Analytics - 如何跟踪内部页面?
- java - 用于线程初始化的同步器是什么?