1

I'm trying to get the code to output when someone only inputs two of their names, but I can't figure it out. I've tried using if (nameFML==null) and (nameFML[2].isEmpty()) but I still get a "exception in thread main java.lang.arrayindexoutofboundsexception: 2" error whenever I type in a name like John Doe. Other than that the program does what it's supposed to.

    import java.util.Scanner;
    public class Assignment3
    {
      public static void main(String[] args)
      {

       //Declaring variables
        String inputName;
        Scanner in = new Scanner(System.in);

       //Asking user for keyboard input.
        System.out.println("What are your first, middle, and last names? ");
        inputName = in.nextLine();

       //Users First Input restated
        System.out.println(inputName);

       //Splitting the string "inputName" up by making spaces(" ") delimiters.
       if (inputName.contains(" "))
        {
          String[] nameFML = inputName.split(" ");

       // Creates new strings from the new "nameFML" variable, which was created from "inputName" being split.
          String firstInitial = nameFML[0].substring(0,1).toUpperCase();
          String middleInitial = nameFML[1].substring(0,1).toUpperCase();
          String lastInitial = nameFML[2].substring(0,1).toUpperCase();

       //The if method determines whether or not the user inputed in three tokens, two, or an incorrect amount.
          if (nameFML.length== 2)
          {
            System.out.println("Your initials are: " + firstInitial + middleInitial);

        //Separated the print the Variation One print command because it's the only way I could get ".toUpperCase" to work properly.
            System.out.print("Variation One: " + (nameFML[1].toUpperCase()));
            System.out.println(", " + nameFML[0]);

            System.out.println("Variation Two: " + nameFML[1] + ", " + nameFML[0]);


          }
          else
          {
            System.out.println("Your initials are: " + firstInitial + middleInitial + lastInitial);

        //Separated the print the Variation One print command because it's the only way I could get ".toUpperCase" to work properly.
            System.out.print("Variation One: " + (nameFML[2].toUpperCase()));
            System.out.println( ", " + nameFML[0] + " " + lastInitial + ".");

            System.out.println("Variation Two: " + nameFML[2] + ", " + nameFML[0] + " " + nameFML[1]);
          }
        }
        else
        {
      System.out.println("Wrong. Please enter your name properly.");
    }
  }
}
1
  • 1
    if (nameFML!=null && !nameFML[2].isEmpty()) Commented Sep 21, 2013 at 3:13

3 Answers 3

1

The problem is that if the string only has two parts, the third element of the array (index 2) isn't empty - it just doesn't exist. Therefore, the code fails at

String lastInitial = nameFML[2].substring(0,1).toUpperCase();

If you move these lines

String firstInitial = nameFML[0].substring(0,1).toUpperCase();
String middleInitial = nameFML[1].substring(0,1).toUpperCase();
String lastInitial = nameFML[2].substring(0,1).toUpperCase();

into the appropriate if statements, everything should work fine. nameFML.length is the correct thing to check.

For future reference, exception in thread main java.lang.arrayindexoutofboundsexception: 2 means that you tried to access index 2 of an array that had less than 3 elements (which occurred when you did nameFML[2]).

Sign up to request clarification or add additional context in comments.

11 Comments

disagree with this.. user an enter "John David Lee". Then it should have 3 values in the array.. If the user enters "David Lee" then your case holds true
@G V, I'm not sure what we disagree about. I agree that the original code works with a three part name, but I thought the question was how to make it also work for two part names like John Doe, which my answer addresses.
@Darby, You made sure that nameFML[2] is only used in places where you know that nameFML.length>2?
I'm not sure what you mean?
@Darby: The only place that you can have nameFML[2] is inside the innermost else statement (the one that is reached if the name has three parts). Otherwise, you could be trying to access the third part of a name that only has 2 parts.
|
1

The task is to find the initials. To do that, you don't necessarily need to know the names or even what each initial is.

You can find the initials in just one line of code:

String initials = input.replaceAll("(?<\\b\\w)\\w*\\s*", "");

This replaces all but the first letters of each word and any trailing spaces with a blank (effe timely deleting them).

The good thing about this code is it will work for any number of names, including just one name or even no names (ie blank input) correctly and importantly without error.

Comments

0

Instead of if-else above, use a for loop

String firstInitial = "";
String middleInitial = "";
String lastInitial = "";
String[] nameFML = inputName.split(" ");
for(int i=o; i<nameFML.length; i++)
{
if(i==0)
 firstInitial = nameFML[0].substring(0,1).toUpperCase();
else if(i=1)
 middleInitial = nameFML[1].substring(0,1).toUpperCase();
else if(i=2)
 lastInitial = nameFML[2].substring(0,1).toUpperCase();
}


System.out.println("Your initials are: " + firstInitial + middleInitial + lastInitial);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.