我正在尝试读取用户输入,然后将这些单词与它们之间的空格连接起来。我在查找循环中的逻辑时遇到了麻烦。我还希望用户能够在完成输入单词后告诉我的程序。这是我到目前为止所做的......它并不多。
LOGIN_URL = 'bookApp:login'
LOGIN_REDIRECT_URL = reverse_lazy('welcome')
答案 0 :(得分:2)
Scanner in = new Scanner(System.in);
String enteredWord = "";
StringBuilder builder = new sb();
System.out.println("Enter words to build a sentence");
enteredWord = in.nextLine();
do {
sb.append(enteredWord);
sb.append(" ");
enteredWord = in.nextLine();
} while (!(enteredWord.equals("exit")));
//you may want to use a special case like %% instead because exit can be in a sentence{
System.out.println(sb.toString());
这应该适用于大部分我现在没有任何地方可以测试它。每次循环时,循环都会在其后面添加一个空格,并要求输入一个新单词。您可以使用userwords += in.nextline() + " ";
,但在循环中我总是会使用stringbuilder来提高效率。
答案 1 :(得分:0)
尝试:
Scanner in = new Scanner(System.in);
String userWords = "";
String currentWord = "";
// now we print a prompt for user
System.out.println("Enter words to build a sentence");
// here is the reading loop
do {
// now we read next line from user
currentWord = in.nextLine();
// now we add the user input to the userWords with " "
userWords += currentWord +" ";
// we end the loop when the currentWord will be empty
} while (!(currentWord.trim().isEmpty()));
// now we print all the words
System.out.println(userWords);