当有人仅输入两个名字时,我试图输出代码,但我无法弄清楚。我尝试使用if (nameFML==null) and (nameFML[2].isEmpty()),但是每当我输入类似John Doe的名称时,我仍然会收到“线程主java.lang.arrayindexoutofboundsexception:2异常”的错误。除此之外,程序可以实现预期的功能。

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

最佳答案

问题是,如果字符串只有两部分,则数组的第三个元素(索引2)不为空-它不存在。因此,代码在以下位置失败

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


如果您移动这些行

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


放入适当的if语句,一切都应该正常工作。 nameFML.length是正确的检查对象。

为了将来参考,exception in thread main java.lang.arrayindexoutofboundsexception: 2表示您尝试访问的元素少于3个的数组的索引2(在您执行nameFML[2]时发生)。

10-06 10:46