[英]Can someone help me understand why I need an IF and WHILE for this answer?
快速提问 - 我已经找到了这个测验问题的正确答案,但我并不完全理解。
这是问题 -
给定一个名为input的Scanner引用变量,该变量与由一系列行组成的输入源相关联,写入每行读取所需的代码,并将它们全部打印在一行上,用空格分隔。
这是答案 -
if(input.hasNext())
System.out.print(input.nextLine());
while (input.hasNext()){
System.out.print(" " + input.nextLine());
}
}
我的问题是 ,为什么需要if和while语句。 我知道我需要先阅读该行,然后将其打印出来。 为什么只有这样才足够:
while(input.hasNext()){
System.out.print(" " + input.nextLine());
}
谢谢
唯一明显的区别是正确答案不会产生以空格开头的输出。
有了这个文件:
foo
bar
baz
您的代码将具有此输出(注意“foo”前面的空格):
foo bar baz
答案的代码将有这个(在“foo”前面没有空格):
foo bar baz
唯一的尊重是在第一个代码中
if(input.hasNext())
System.out.print(input.nextLine());
while (input.hasNext()){
System.out.print(" " + input.nextLine());
}
}
你将打印“”-space-然后是字符串,但在第二个,你将从行的开头开始,然后它将在单词之间放置空格
“太空”第一名第二名
是不同的
第一个第二个第三个//首先没有空格
使用集合中的分隔符创建String时遇到的常见问题是如何避免多余的前导或尾随空间。 这就是额外的if语句实现的目的。 还有其他几种解决方法,下面我提供两种选择。
你也可以这样做:
// first build the output string using a StringBuilder
StringBuilder sb = new StringBuilder();
while(input.hasNext()) {
sb.append(input.nextLine()).append(" ");
}
// if there was input, the StringBuilder will have an extra space at the end
if (sb.length() > 0) {
// in that case remove the space and print the result
sb.deleteCharAt(sb.length() - 1);
System.out.println(sb);
}
或者为了更有趣,一个递归的解决方案:
private String read(Scanner input) {
if (!input.hasNext()) {
return "";
}
String head = input.nextLine();
if (input.hasNext()) {
return head + " " + read(input);
}
else {
return head;
}
}
问题是输出将以空格开头。 你可以把空间放在最后,它会正常工作:
System.out.print(input.nextLine() + " ");
如果这仍然导致问题,也许这将工作:
while(input.hasNext()){
System.out.print(input.nextLine());
if(input.hasNext())
System.out.print(" ");
}
我没有测试过它,但除了最后一行之外,它应该为每一行添加一个空格。
这是另一种方法(我找不到我最初看到类似用法的地方):
String spacer = "";
while(input.hasNext()){
System.out.print(spacer + input.nextLine());
spacer = " ";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.