我正在尝试编写一个程序,它接受用户输入的单词并使用这些单词构建一个句子。因此,如果您输入“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);
}
}
答案 0 :(得分:1)
将您的代码更改为以下内容:
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: ");
//remove the first prompt here..
do {
word = scnr.next();
if(word.equalsIgnoreCase(SENTINEL)) //exit loop if "done" was input
break;
count++;
sentence += word + " ";
} while (!(word.equalsIgnoreCase(SENTINEL)));
System.out.println(sentence);
}
您需要删除循环外的第一个提示,否则它不会将第一个输入添加到您的字符串中。收到“完成”后,我添加了一张支票。
这可能是学校的问题,因此您使用sentence += word
。但是,为了累积添加字符串,最好使用StringBuilder
。
答案 1 :(得分:0)
只需以简单的方式重写你的do while块。
word = scnr.nextLine();
while (!(SENTINEL.equalsIgnoreCase(word))) {
sentence += word + " ";
word = scnr.nextLine();
count++;
}