当有人只输入他们的两个名字时,我试图让代码输出,但我无法弄清楚。我尝试过使用 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.");
}
}
}