gpt4 book ai didi

java - 具有两个字符串的基本并行数组

转载 作者:行者123 更新时间:2023-12-01 13:57:36 24 4
gpt4 key购买 nike

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

    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)

再次感谢大家的意见。

最佳答案

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

stateName[i] = keyboard.nextLine();

应该是这样的:

searchState = keyboard.nextLine();

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

 if(stateName[i].matches(capName[i]) )

关于java - 具有两个字符串的基本并行数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19542715/

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