I want to write a loop that prompts the user to input their first middle and last name, I then want to validate that input by searching for the white spaces in between each name.
Example: First Middle Last
What I'm looking for is some thing like the following.
Pseudo Code: if name contains 2 white spaces and their are less than 3 white space in name the operation has been successful other wise tell the user to re-input their first middle and last name.
How can I go about doing this?
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
boolean isName = false;
String name = "";
int x = name.length();
Scanner input = new Scanner(System.in);
while(!isName) // Probably better to remove the while loop entirely
{
System.out.print("Please input your 'First Middle Last' name: ");
name = input.nextLine();
name.trim(); // To remove any leading or trailing white spaces
for(int i = 0; i < x; i++)
{
if(name.lastIndexOf(' ', i) == 2 && name.lastIndexOf(' ', i) < 3)
{
isName = true;
break;
}
else
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
name = name.trim();
System.out.print("\nInvalid input");
}
}
}
}
The above produces an infinite loop and logically I understand why.