我被要求做以下事情:
更改介绍性问题 1 以按姓氏字母顺序显示输入的姓名。问题 1:编写一个创建 5 x 2 数组的程序。第一列代表名字,第二列将存储姓氏。让用户输入 5 个全名(名字和姓氏)以存储在这个二维数组中。完成所有输入后,显示名称,但将它们显示为 LastName,第一个首字母。
我现在意识到下面概述的方法不是攻击这个程序的正确/最有效的方法,但我仍然对为什么程序失败的原因感到困惑。当我在eclipse中运行程序时,它会打印一次问号行,然后抛出以下异常:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:TwoD6.main(TwoD6.java:36) 的 java.lang.String.charAt(Unknown Source) 处的 0
它似乎在第二次运行时失败了,我不明白为什么会这样。我尝试在变量类型之间更改它,担心不接受 char 的数值(charAt 命令最初在 if 语句中),以及在用户之前填充数组(认为也许错误来自 java 不接受字符串在位置 0 处有字符)。
import java.util.Scanner;
public class TwoD6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Input 5 full names (first and last).");
String [][] d2 = { { " "," " },
{" "," "},
{" "," "},
{" "," "},
{" "," "} };
//new String[5][2]; initial string declaration, which I previously thought could be the source of the issues
for(int i = 0; i < d2.length; i++)
{
d2 [i][0] = sc.next();
d2 [i][1] = sc.next();
}
for(int i = 0; i < d2.length-1; i++)
{
char c = d2[i][1].charAt(0);
char d = d2[i+1][1].charAt(0);
int e = c; int f = d;
if(e < f)
{
System.out.println("????????????????"); //implemented to see how many times the loop runs; currently prints once
String a = ""; String b = ""; //switchers
d2[i][0] = a; d2[i][1] = b;
d2[i][0] = d2[i+1][0]; d2[i+1][0] = a;
d2[i][1] = d2[i+1][1]; d2[i+1][1] = b;
}
}
for(int i = 0; i < d2.length; i++) //printing the array
{
char firstChar = d2[i][0].charAt(0);
System.out.println(d2[i][1] + ", " + firstChar + ".");
}
}
}
我会很感激你能给我的任何解释。我对解决这个问题并不感兴趣,因为我已经编写了一个更好的程序,但我想知道 charAt() 命令和下次怎么修。谢谢!