0

当我测试它时,它构建得很好。但是当我运行它时,只会出现介绍和用户输出问题(这是它应该做的),但是当我输入答案时会出现错误:

    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)

再次感谢大家的意见。

4

3 回答 3

1

由于i未初始化(在代码段中)

stateName[i] = keyboard.nextLine();

应该是这样的:

searchState = keyboard.nextLine();

这种比较是没有意义的,因为它永远不会匹配(应该是上面的 searchState):

 if(stateName[i].matches(capName[i]) )
于 2013-10-23T13:17:38.943 回答
0

问题1

 stateName[i] = keyboard.nextLine();

问题 2

 for(i=0; i < 50; i++)
{
stateName[0] = "Alabama";
stateName[1] = "Alaska";
.....
capName[0] = "Montgomery";
capName[1] = "Juneau";
.....
}

我认为这应该是 stateName[i] = "Alabama";

问题 3

你错过了"{" "}"for 循环中的

for(i=0; (!found) && (i < stateName.length); 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.");
于 2013-10-23T13:16:39.953 回答
0

您有很多很好的建议来改进您的代码,我将尝试实施这些建议。

错误的原因是您的 for 循环。

for(i=0; (!found) && (i < stateName.lenth); i++)

数组的长度将返回 50,但是您的索引从 0 到 49 并且因为您永远找不到匹配项,所以它会遍历整个循环。

于 2013-10-23T13:30:08.093 回答