为什么包含并互相混淆?

问题描述 投票:0回答:1
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。请帮忙,非常感谢!

java add contains
1个回答
0
投票

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

添加此代码后,您的代码将编译并运行,但您将获得一个空数组。这是因为线i = j;

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

© www.soinside.com 2019 - 2024. All rights reserved.