如何仅使用 space 字符从 Java 中的输入字符串注册一个字符串

How to just take a space character to register a String from input string in Java

我有一个问题,我无法在任何地方找到有关从输入中获取字符串的逻辑的解决方案。如果你帮我解决这个问题,我会很高兴。首先,我的问题是我只需要一个 space 字符就可以从 Java 中的输入注册到一个字符串中,因为我希望我的程序的 hasNext() 方法为 return false。 正如某些消息来源所说,“对于 return false value 的 hasNext() 方法,下一个字符必须是“whitespace”,因此对于 hasNext() 来说,只有一个 space 字符就足够了方法 return false 并退出循环。

示例代码如下;

Scanner scan = new Scanner(System.in);
    int counter=0;
    while (scan.hasNext()) { /*When I just type a space
        character to the console and then
        scan.hasNext() doesn't return false.
        so the program never get out from the loop*/
        counter++;
        System.out.println(counter);
        String s = scan.next();
    }
    scan.close();
    System.out.println("It's outed!");

在控制台输入 space 字符或不输入字符并按下回车按钮后,s 的字符串必须像消息来源所说的那样退出循环;

String s = " ";

当我尝试将上面的 space 字符放入输入的字符串中,然后按下回车按钮时。我的控制台没有做任何处理,上面的计数器也没有增加。在按下输入 button.The 控制台后,我写的上面的字符不会传递到新行。我研究了这种情况,但我看不到任何相关信息。

1 - 我怎样才能只从输入中获取 space 字符或不使用任何字符将其注册到 Java 中的字符串中而不会出现上述问题?

2 - 上面的循环可能还有另一种退出方式。如果有其他解决方案。我期待着听到你的消息。

感谢您的帮助和理解。祝你有美好的一天!

不知道你是否想要这样的东西,试试看并写评论

Scanner sc = new Scanner(System.in);
int counter = 0;
String str = "";
while (! (str = sc.nextLine()).equals(" ")) {

  // ==== options ===== //

 // if you want when user not typing anything [ Empty ]
  if (str.isEmpty()) {
    break;
  }

  // or if user entred "exit"
  if (str.equals("exit")) {
    System.out.println("Exit");
    break;
  }

 // ================== //
  counter++;
  System.out.println(counter + " - " + str);
}

// str = " "; ended the while loop
System.out.println("--- out ---");