[英]I keep getting string index out of bounds exception and I have no idea why
因此,我正在讀取 .txt 文件,並且不斷收到字符串索引越界異常。 我一直在嘗試查找重復的單詞並在向數組添加單詞時保持數組排序。 我以為我的問題是在數組中沒有單詞或只有一個單詞時嘗試對數組進行排序和搜索。 前面有**的那一行是問題行。 它的第 129 行
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();
print();
}
public static void readIn()
{
File inFile = new File("carol.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[dict.length*2];
for(int i = 0; i < index; i++)
{
newAr[i] = dict[i];
}
if(dict.length < 2)
{
newAr[index] = word;
index++;
}
else
{
bubbleSort(word);
if(!wordHasDuplicate(word))
{
newAr[index] = word;
index++;
}
}
dict = newAr;
}
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);
}
}
public static void print()
{
try
{
FileWriter outFile = new FileWriter("dict.txt");
for(int i = 0; i < index; i++)
{
outFile.write(dict[i]);
outFile.write(" \n ");
}
outFile.close();
}
catch (IOException e)
{
System.out.println("Error ");
}
}
public static void bubbleSort(String word)
{
boolean swap = true;
String temp;
int wordBeforeIndex = 0;
String wordBefore;
while(swap)
{
swap = false;
wordBefore = dict[wordBeforeIndex];
for(int i = 0; (i < word.length()) && (i < wordBefore.length()) i++)
{
**if(word.charAt(i) < wordBefore.charAt(i))**
{
temp = wordBefore;
dict[wordBeforeIndex] = word;
dict[wordBeforeIndex++] = temp;
wordBeforeIndex++;
swap = true;
}
}
}
}
public static boolean wordHasDuplicate(String word)
{
int low = 0;
int high = dict.length - 1;
int mid = low + (high - low) /2;
while (low <= high && dict[mid] != word)
{
if (word.compareTo(dict[mid]) < 0)
{
low = mid + 1;
}
else
{
high = mid + 1;
}
}
return true;
}
}
錯誤如下圖所示:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at BuildDict.bubbleSort(BuildDict.java:129)
at BuildDict.addToDict(BuildDict.java:60)
at BuildDict.checkRegex(BuildDict.java:90)
at BuildDict.readIn(BuildDict.java:30)
at BuildDict.main(BuildDict.java:14)
檢查 wordBefore 的長度作為 for 循環的第二個條件:
for(int i = 0; (i < word.length()) && (i < wordbefore.length()); i++)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.