gpt4 book ai didi

java - 我正在尝试调整数组大小,但不断出现索引越界异常

转载 作者:行者123 更新时间:2023-12-02 04:16:22 24 4
gpt4 key购买 nike

我正在尝试从 .txt 文件创建字典。我认为问题出在我的 addToDict 方法中。我正在尝试在数组已满时调整其大小,因为我正在从未知大小的文本文件中读取数据,但我只能使用数组。当我打印数组时出现越界异常。我不知道出了什么问题,我已经在这个项目上工作了好几天了。我的 addToDict 方法中的 else 语句也遇到问题。这也是越界异常

import java.io.*;
import java.util.Scanner;
import java.util.regex.*;

public class BuildDict {
static String dict[] = new String[20];
static int index = 0;

public static void main(String args[]) {
readIn();
}

public static void readIn() {
File inFile = new File("alice.txt");
try {
Scanner scan = new Scanner(inFile);
while (scan.hasNext()) {
String word = scan.next();
if (!Character.isUpperCase(word.charAt(0))) {
checkRegex(word);
}
}
scan.close();
} catch (IOException e) {
System.out.println("Error");
}
}

public static void addToDict(String word) {

if (index == dict.length) {

String newAr[] = new String[index * 2];
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
dict = newAr;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}
} else {
dict[index] = word;
index++;
}
}

public static void checkRegex(String word) {
String regex = ("[^A-Za-z]");
Pattern check = Pattern.compile(regex);
Matcher regexMatcher = check.matcher(word);
if (!regexMatcher.find()) {
addToDict(word);
}
}
}

最佳答案

您尚未将新数组分配给 dict

if (index == dict.length) {
for (int i = 0; i < index; i++) {
newAr[i] = dict[i];
}
newAr[index] = word;
index++;
for (int j = 0; j < index; j++) {
System.out.println(newAr[j]);
}

// Assign dict to the new array.
dict = newAr;
} else {
dict[index] = word;
index++;
}

关于java - 我正在尝试调整数组大小,但不断出现索引越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33270284/

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