[英]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隱式返回-1,則會發生這種情況),但是當我嘗試測試ArrayList中的string,結果為true ,指示ArrayList具有特定的字符串,但在調用該字符串的索引時仍返回-1。 請幫忙,非常感謝!
您正在獲取ArrayIndexOutOfBoundsException
因為您正在嘗試查找列表中不存在的字符串的索引。 要解決此問題,您應該添加!
在list.contains(s.substring(i, j))
之前list.contains(s.substring(i, j))
添加此代碼后,您的代碼可以編譯並運行,但是會得到一個空數組。 這是因為行i = j;
。
為什么? 因為最初您是在做int j = i;
,然后執行邏輯運算來查找單詞長度(如果它是字母),然后執行j++
,然后一旦確定了長度,則執行i = j;
。 因此,基本上在i
和j
發生的事情將始終具有相同的值。 因此,當您執行子字符串時,由於i
和j
相同,因此會返回j
。 Try commenting this line i = j;
您應該會看到輸出。 我建議您稍微改變一下邏輯以找到單詞並將其添加到列表中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.