[英]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.