Reads the user's first and last name (an entire line as a single string), then prints the last name followed by a comma and the first initial. Ensure the code re-prompts until the user types a name that is at least 5 letters total in length and has at least one space in it. For example:
Type your name: Jessica Miller
Your name is: Miller, J.
A few questions I have about my code:
- Is there a difference between breaking out of a loop with a
break
statement, and meeting the condition forcorrectName
? - Did I make my program do unnecessary things? I'd like to answer this for myself, but I may've made it unnecessarily complex, or even buggy, due to my thought process. For instance, can I check if there's a space in my first conditional, where I check if the length of the line is greater than or equal to five?
Any feedback is welcome!
Scanner console = new Scanner(System.in);
boolean correctName = false;
while(correctName != true) {
System.out.print("Type your name: ");
String line = console.nextLine();
if(line.length() >= 5) {
StringTokenizer lineTokens = new StringTokenizer(line);
while(lineTokens.hasMoreTokens()) {
if(lineTokens.countTokens() >= 2) {
String first = lineTokens.nextToken();
String last = lineTokens.nextToken();
String name = (last + ", " + first.substring(0, 1) + ".");
System.out.println("Your name is: " + name);
correctName = true;
} else {
String checkSpace = lineTokens.nextToken();
for(int i = 0; i < checkSpace.length(); i++) {
if(checkSpace.charAt(i) == ' ') {
break;
} else {
System.out.println("Error, must be at least 5 chars with a space.");
break;
}
}
}
}
} else {
System.out.println("Error, must be at least 5 chars with a space.");
}
}