Checking string formats in Java?

there are problems that do something for the class i am taking since i missed a class or two. (I know he was looking down to “do some homework,” but I'm not looking for that.)

The assignment looks like this:

Write a program to do the following:

  • Request to enter first name, last name and last name as one line (using any combination of upper and lower case letters).
  • Make sure the name is entered in the correct format (3 names separated by spaces). If the input is incorrect, keep asking for input again until the format is correct.
  • Cap only the first letters of each part of the name and print the revised name.
  • Print out initials for this name.
  • Print the name in the format: Lastname, Firstname, MI.

The main problem I faced was the second part of the assignment; I got the first part and I'm sure I can handle the rest after I get the second setting.

import java.util.*;

public class TestStrings
public static void main(String[] args) 
    Scanner key = new Scanner(;
    String name;
    System.out.print("Enter your name as 'First Middle Last': ");
    name = key.nextLine();



From what I've put together, do I need to use string.split? I'm not sure how to do this though, since I need to check that there are three spaces that are not just next to each other or something like "John (three spaces) Doe". I am guessing this will be some kind of loop to validate the input for the name.

Trap 22 is that I cannot use arrays or StringTokenizer. I have to use the substring method.

Any help would be greatly appreciated. Thank you .: D


source to share

5 answers

To point you in the right direction to find the first name (since you cannot use arrays):

String firstName = input.substring(0, input.indexOf(" "));


This will give you the substring from start to first place. If you're researching indexOf methods and substrings, you should get away from there.



You can use the substring and indexOf functions of the String class to get what you want.

String # indexOf : get the position of a string within a string.

String # substring : Get the substring contained in the string.

String s = "Luiggi Mendoza J.";
String x;
while(s.indexOf(" ") > 0) {
    x = s.substring(0, s.indexOf(" "));
    s = s.substring(s.indexOf(" ") + 1);
x = s;


The program output will be:





Have a look at the matching method if you know how to use a regular expression. If you don't think about indexOf and substring methods.



Use a while loop to continually check to see if the user is entering a string with three parts separated by a space character ' '

, then use a function split()

to check the three parts of the string. Using substring()

as shown here you can get the names separately:

public static void main ( String [] args )
    String name = "";
    boolean ok = false;
    Scanner key = new Scanner( );

    while ( !ok )
        System.out.print( "Enter your name as 'First Middle Last': " );
        name = key.nextLine();
            if ( name.split( " " ).length == 3 )
                ok = true;
        catch ( Exception e ){ }

    if ( ok )
       String firstName = name.substring(0, name.indexOf(" "));
       String middleName = name.substring(firstName.length()+1, 
                                       name.lastIndexOf(" "));
       String surname = name.substring(middleName.length()+firstName.length()+2,




This works using Pattern / Matcher and regular expressions. Also protects against 1 strings when tuning the body.

private static String properCase(String str) {
    return str.substring(0, 1).toUpperCase()
            + (str.length() >= 1 ? str.substring(1).toLowerCase() : "");

public static void main(String[] args) {

    boolean found = false;
    do {
        Scanner scanner = new Scanner(;
        System.out.print("Enter your name as 'First Middle Last': ");
        Pattern p = Pattern.compile("\\s*(\\w+?)\\s(\\w+?)\\s(\\w+)+\\s*");
        Matcher m = p.matcher(scanner.nextLine());
        found = m.find();
        if (found) {
            String first =;
            String middle =;
            String last =;

            String revised = properCase(first) + " " + properCase(middle)
                    + " " + properCase(last);

                    .printf("%s %s %s.\n", properCase(last),
                            properCase(first), middle.substring(0, 1)
    } while (!found);




All Articles