当我测试它时,它构建得很好。但是当我运行它时,只会出现介绍和用户输出问题(这是它应该做的),但是当我输入答案时会出现错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50
at statecapitals.StateCapitals.main(StateCapitals.java:141)
现在我知道我是新手,但我认为错误是我的数组不对应,我不确定我做错了什么。任何帮助将不胜感激。这是我所拥有的:
String[] stateName = new String[50];
String[] capName = new String[50];
int i;
for(i=0; i < 50; i++)
{
stateName[0] = "Alabama";
stateName[1] = "Alaska";
.....
capName[0] = "Montgomery";
capName[1] = "Juneau";
.....
}
boolean found = false;
Scanner keyboard = new Scanner(System.in);
System.out.println("This program is designed...");
System.out.println("Please enter the name of a U.S. state (please enter capitalized):");
stateName[i] = keyboard.nextLine();
for(i=0; (!found) && (i < stateName.lenth); i++)
if(stateName[i].matches(capName[i]) )
System.out.print(The capital of " + stateName + " is " + capName);
found = true;
if(!found)
System.out.println("The name you entered was not on the list.");
*更新和编辑:最麻烦的代码行是:
stateName[i] = keyboard.nextLine();
谢谢大家的帮助,我做了一些改变:
int i;
for(i=0; i < 49; i++)
{
stateName[i+1]
.....
capName[i+1]
...
}
另外,我在底部的 for 循环中添加了大括号。现在,当我运行它时,它会在线停止:
if(capName[i].matches(stateName[i]) )
这次的错误是:
Exception in thread "main" java.lang.NullPointerException
at statecapitals.StateCapitals.main(StateCapitals.java:146)
再次感谢大家的意见。