为什么 contains 和 add 会互相混淆?

Why are contains and add confusing each other?

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 将隐式 return - 1), 但是当我尝试测试ArrayList中的字符串是否存在时,结果是true,说明ArrayList有一定的字符串但还是return -1时要求字符串的索引。请帮忙,非常感谢!

您得到 ArrayIndexOutOfBoundsException 是因为您正在尝试查找列表中不存在的字符串的索引。要解决此问题,您应该在 list.contains(s.substring(i, j))

之前添加 !

添加这个之后,你的代码会编译并且运行但是你得到一个空数组。发生这种情况是因为第 i = j; 行。

为什么? 因为最初你在做 int j = i;,然后你的逻辑是找到单词长度,如果它是字母的,做 j++ 然后一次你有长度,你做 i = j;。所以基本上 ij 中发生的事情将始终具有相同的值。因此,当您执行子字符串时,会返回注释,因为 ij 相同。 Try commenting this line i = j; 你应该会看到输出。我建议你稍微改变你的逻辑来找到单词并将其添加到列表