0

So new Java developer here, been at it for a week and decide to get my hands dirty.

I have been trying to create an application wherein a user can register for an account. I am at the part where the user has to enter their full name, and the program has to ensure there is a space between the name or else it should tell the user to re-enter the name with a space.

Currently, I have tried to setup a while loop, and make it repeat whilst the indexOf condition is <=0 which means there is no space. However, I'm not sure how I'd make it move on once the user has successfully entered a name with a space.

My current code is as follows:

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


        }
 }

All help appreciated.

Thanks.

xingbin
  • 27,410
  • 9
  • 53
  • 103
AmsKumar
  • 93
  • 1
  • 10
  • Alternatively, ask the user for the first name and second name separately and you put in the space yourself. – achAmháin Jul 03 '18 at 14:57

1 Answers1

2

You need call input.indexOf(' ') < 0, since the first character index is 0.

And you did not break the loop when secondInput contains whitespace.

You can just use one string to achieve this:

while (input.indexOf(' ') < 0) {
    System.out.println("Please retype your full name with a space: ");
    input = scanner.nextLine();
}
System.out.println("Program has worked");
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • 1
    You could also work with a for loop. `for(String input = scanner.nextLine(); input.indexOf(' ') < 0; input = scanner.nextLine()){...}` – Lino Jul 03 '18 at 14:25