gpt4 book ai didi

java - Java简介: How to use an if statment when a string doesn't exist

转载 作者:行者123 更新时间:2023-11-30 04:13:51 25 4
gpt4 key购买 nike

当有人只输入他们的两个名字时,我试图让代码输出,但我无法弄清楚。我尝试过使用 if (nameFML==null) 和 (nameFML[2].isEmpty()) 但每当我仍然收到“thread main java.lang.arrayindexoutofboundsexception: 2”错误时我输入一个名字,比如 John Doe。除此之外,程序会执行它应该执行的操作。

    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 是要检查的正确内容。

供将来引用,thread main java.lang.arrayindexoutofboundsException: 2 中的异常:2 表示您尝试访问少于 3 个元素的数组的索引 2 (当您执行 nameFML[2] 时发生的情况)。

关于java - Java简介: How to use an if statment when a string doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com