我正在尝试阅读用户输入,然后将这些单词与它们之间的空格连接起来。我在弄清楚循环中的逻辑时遇到了麻烦。我还希望用户输入完文字后能够告诉我的程序。到目前为止,这是我所拥有的……不多。

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);

10-04 11:39