While循环查找空格字符-Java

时间:2018-07-03 14:14:16

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

所以这里的新Java开发人员已经忙了一个星期,然后决定弄脏我的手。

我一直在尝试创建一个用户可以在其中注册帐户的应用程序。我是用户必须输入其全名的地方,该程序必须确保名称之间有空格,否则它应该告诉用户用空格重新输入名称。

当前,我尝试设置一个while循环,并在indexOf条件为<= 0时重复它,这意味着没有空间。但是,我不确定用户成功输入带空格的名称后如何继续使用它。

我当前的代码如下:

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


        }
 }

感谢所有帮助。

谢谢。

1 个答案:

答案 0 :(得分:2)

您需要呼叫input.indexOf(' ') < 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");