gpt4 book ai didi

Java 数组索引越界异常表示数组比实际小

转载 作者:行者123 更新时间:2023-12-01 11:25:43 25 4
gpt4 key购买 nike

我的程序正在比较两个 for 循环内的两个字符串。运行时,它会产生错误:Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: 2,即使数组已初始化以获得足够的空间。代码行是:

if(keywords[a].equals(tokenizedString[b])&&tokenizedString[a].equals("1"))

keywords 的初始化位置:

String[] keywords={"0","add","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};

初始化tokenizedString的位置:

String[] tokenizedString={"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};

为什么当我运行它时,当该语句中使用的唯一两个数组明显更大时,它是否说“2 越界”?

代码的相关部分:

import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {
public static void main(String[] args) {
final int KEYWORDS = 3;
String[] keywords =
{"0", "add", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0"};
Scanner scan = new Scanner(System.in);
String[] tokenizedString =
{"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0"};
int stringCounter = 1;
String input = scan.nextLine();
StringTokenizer st = new StringTokenizer(input, " ");
String answer = null;
while (st.hasMoreElements()) {
answer = (String) st.nextElement();
System.out.println(answer);
tokenizedString[stringCounter] = answer;
stringCounter++;
}
String[] functions;
functions = new String[10];
functions = testForKeywords(tokenizedString, keywords, stringCounter, KEYWORDS);
int[] numbers = new int[10];
String[] numberss = {"1", "2"};
numbers = testForNumbers(tokenizedString, numberss, stringCounter, 2);
}

public static int[] testForNumbers(String[] tokenizedString, String[] keywords, int inputs,
int numbKeywords) {
int[] functions = new int[inputs + 1];
int funCounter = 0;
for (int a = 0; a <= numbKeywords; a++) {
for (int b = 0; b <= inputs; b++) {
if (keywords[a].equals(tokenizedString[b]) && tokenizedString[a].equals("1")) {
System.out.println("Yay");
functions[funCounter] = 1;
funCounter++;
}
}
}
return functions;
}
}

最佳答案

您对发生错误时keywords 的值感到困惑。

您的错误发生在 testForNumbers() 中,您有一个本地(方法范围)变量 keywords 作为参数传入。如果您查看调用此函数的位置,则会在该位置传入 numberss

numberss 只有两个成员 - 因此只有索引 01 - 尝试访问索引 2确实会在运行时抛出这个异常

关于Java 数组索引越界异常表示数组比实际小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30813665/

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