我正在嘗試編寫一個程序,該程序需要用戶輸入的單詞並使用這些單詞構建一個句子。所以如果你輸入「Hello」和「World」,它將返回「Hello World」。但是,如果我輸入「我」,「愛」和「狗」,它會返回「愛狗完成」。 (做是我的定點用戶退出我不知道如何做到這一點將用戶輸入的單詞組合成一個語句
import java.util.Scanner;
public class SentenceBuilder {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String word = " ";
String sentence = " ";
final String SENTINEL = "done";
double count = 0;
System.out.println("Enter multiple words: ");
System.out.println("Enter done to finish: ");
word = scnr.nextLine();
do {
word = scnr.nextLine();
count++;
sentence += word + " ";
} while (!(word.equalsIgnoreCase(SENTINEL)));
System.out.println(sentence);
}
}
APRT,你應該考慮'StringBuilder'或'StringBuffer'作爲字符串是不可改變的 – Pragnani
@Luke哈丁嘗試下面我的解決方案.. – user3437460