【问题标题】:While loop to find space character - JavaWhile循环查找空格字符-Java
【发布时间】:2018-12-11 21:37:31
【问题描述】:

所以这里是新的 Java 开发人员,在这里工作了一周,并决定亲自动手。

我一直在尝试创建一个用户可以注册帐户的应用程序。我在用户必须输入他们的全名的部分,并且程序必须确保名称之间有空格,否则它应该告诉用户重新输入带有空格的名称。

目前,我尝试设置一个 while 循环,并在 indexOf 条件为

我目前的代码如下:

 public static void companyEmail() {

        System.out.println("+--------------------------------+");
        System.out.println("|   Company Email Registration   |");
        System.out.println("+--------------------------------+");

        Scanner scanner = new Scanner(System.in);
        System.out.print("Please enter your full name: ");
        String input = scanner.nextLine();
        while (input.indexOf(' ') <=0) {
            System.out.println("Please retype your full name with a space: ");
            String secondInput = scanner.nextLine();
            if(secondInput.indexOf(' ') <=0) {
                break;
            }

            System.out.println("Program has worked");


        }
 }

感谢所有帮助。

谢谢。

【问题讨论】:

  • 或者,分别询问用户的名字和名字,然后您自己输入空格。

标签: java loops while-loop java.util.scanner do-while


【解决方案1】:

您需要调用input.indexOf(' ') &lt; 0,因为第一个字符索引是0。

当secondInput 包含空格时,您没有中断循环。

您可以只使用一个字符串来实现:

while (input.indexOf(' ') < 0) {
    System.out.println("Please retype your full name with a space: ");
    input = scanner.nextLine();
}
System.out.println("Program has worked");

【讨论】:

  • 您也可以使用 for 循环。 for(String input = scanner.nextLine(); input.indexOf(' ') &lt; 0; input = scanner.nextLine()){...}
猜你喜欢
  • 2016-08-27
  • 2019-04-26
  • 1970-01-01
  • 2021-12-19
  • 2012-10-05
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 1970-01-01
相关资源
最近更新 更多