【发布时间】:2019-03-07 07:34:25
【问题描述】:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author user
*/
public class Exercise1 {
public static void main(String[] args) throws FileNotFoundException {
int numOfLines = 0;
int numOfWords = 0;
Scanner scan1 = new Scanner(new File("C:/Users/user/Downloads/exercise.txt"));
ArrayList<String> list = new ArrayList<>();
int[] arr = new int[1000];
while (scan1.hasNextLine()) {
String s = scan1.nextLine();
for (int i = 0; i < s.length(); i++) {
if (!Character.isAlphabetic(s.charAt(i))) {
} else {
//is an alphabet
int j = i; //stop index;
//find the complete word
while (Character.isAlphabetic(s.charAt(j))) {
j++;
if (j == s.length()) {
break;
}
}
i = j; //set to last index
//check if list has the string
if (list.contains(s.substring(i, j))) {
list.add(s.substring(i, j));
System.out.println(list.size());
arr[list.indexOf(s.substring(i, j))]++;
} else {
arr[list.indexOf(s.substring(i, j))]++;
}
numOfWords++;
}
}
}
System.out.println(Arrays.toString(list.toArray()));
System.out.println(numOfWords);
}
}
我试图从包含字母、数字和特殊字符的文本文件中检索文本,但 contains 方法和 add 方法似乎相互混淆。
当找到一个单词字符串时,我通过检查该单词字符串是否包含在 ArrayList 中来使代码工作,如果是,则特定字符串的索引将用作另一个中的增量点数组(记录字数)。
但是当我运行代码时,会抛出 ArrayIndexOutOfBoundException 异常,这意味着获得的索引是 -1(如果找不到字符串并且 ArrayList 将隐式返回 -1,则会发生这种情况),但是当我尝试测试ArrayList 中是否存在字符串结果为true,表示ArrayList 有某个字符串,但调用该字符串的索引时仍返回-1。请帮忙,非常感谢!
【问题讨论】:
-
表示 ArrayList 具有特定字符串但仍返回 -1 - 你 100% 确定吗?在我看来,错误可能与
arr[list.indexOf(s.substring(i, j))]++;有关,原因有两个:1) 在if块中,list.indexOf可能返回一个大于arr大小的数字。 2) 在else块中,您调用list.indexOf但list.contains刚刚返回false(所以结果显然是-1)。两种方式都会生成一个ArrayIndexOutOfBoundsException,您应该包含完整的堆栈跟踪并将我们指向它所指的行。 -
当我在 "list.contains(s.substring(i, j))" 前面添加一个感叹号时,输出将是一个大小为 1 的空 ArrayList。
-
我认为列表不可能返回大于数组大小的索引,因为文本文件中的单词总数小于数组大小的一半(100)。
-
不要 think: debug :) 请用完整的堆栈跟踪更新问题。
-
不知道怎么调试哈哈,编译代码等于调试吗?