使用 do while 循环连接
Concatenation using a do while loop
我正在尝试读取用户输入,然后将这些词与 space 连接起来。我无法弄清楚循环中的逻辑。我还希望用户在输入完单词后能够告诉我的程序。这是我目前所拥有的……并不多。
Scanner in = new Scanner(System.in);
String userWords = "";
int number = 0;
System.out.println("Enter words to build a sentence");
userWords = in.nextLine();
int i = 1;
do {
System.out.println(userWords);
i++;
} while (!(userWords.equals(null))); {
System.out.println(userWords + " ");
}
试试:
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);
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());
这应该在大多数情况下都有效,我现在没有任何地方可以对其进行测试。每次循环都会添加后面带有 space 的单词,并要求输入一个新单词。您也可以使用 userwords += in.nextline() + " ";
但在循环中我总是会使用 stringbuilder 来提高效率。
我正在尝试读取用户输入,然后将这些词与 space 连接起来。我无法弄清楚循环中的逻辑。我还希望用户在输入完单词后能够告诉我的程序。这是我目前所拥有的……并不多。
Scanner in = new Scanner(System.in);
String userWords = "";
int number = 0;
System.out.println("Enter words to build a sentence");
userWords = in.nextLine();
int i = 1;
do {
System.out.println(userWords);
i++;
} while (!(userWords.equals(null))); {
System.out.println(userWords + " ");
}
试试:
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);
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());
这应该在大多数情况下都有效,我现在没有任何地方可以对其进行测试。每次循环都会添加后面带有 space 的单词,并要求输入一个新单词。您也可以使用 userwords += in.nextline() + " ";
但在循环中我总是会使用 stringbuilder 来提高效率。