IT網絡/編程學生在這里試圖完成一項作業,我遇到了一個障礙。我們的任務是讀取文本文件,將單詞放入 ArrayList 中,并對內容執行字符串操作。我能夠將單詞拉入ArrayList,按升序對內容進行排序,刪除任何少于四個字符的單詞,刪除重復的條目,并刪除數字。然而,我發現帶有撇號的單詞正在被“切斷”。像“不會”和“不能”這樣的詞被放入我的 ArrayList 中,作為“會”和“不能”。我已經為我的掃描儀對象嘗試了不同的分隔符,但我似乎找不到一個可以在單詞中保留撇號而不在撇號之后切斷單詞的分隔符。import java.io.File;import java.io.FileNotFoundException;import java.util.ArrayList;import java.util.Collections;import java.util.LinkedHashSet;import java.util.Scanner;public class textFile { public static void main(String[] args) throws FileNotFoundException { // Scanner object reads in the required text file to the "words" ArrayList. Scanner sc = new Scanner(new File("textfile.txt"), "UTF-8"); ArrayList<String> words = new ArrayList<String>(); while (sc.hasNext()) { sc.useDelimiter("[^A-Za-z]"); words.add(sc.next().toLowerCase()); } // Closes the Scanner object used just above. sc.close(); // Sorts the "words" ArrayList in ascending order. Collections.sort(words); // Creates the "wordsNoDuplicates" ArrayList. Removes duplicate strings. LinkedHashSet<String> wordsNoDup = new LinkedHashSet<String>(words); // Removes all words containing less than four characters. wordsNoDup.removeIf(u -> u.length() < 4); // Prints the total number of words in the "wordsNoDup" ArrayList System.out.println("Total Number of Words: " + wordsNoDup.size() + "\n"); // Calculate and print the average word length. // double avgWordLength = 21186 / wordsNoDup.size(); System.out.println("Average Word Length: " + 7.0 + "\n"); // Print out the "words" ArrayList. Intended for debugging. System.out.print(wordsNoDup); System.out.println(); }}同樣,像“不能”,“不應該”和“不會”這樣的詞被拉進來作為“可以”,“應該”和“會”。似乎是撇號和任何東西,它被丟棄。我會公開承認我不是一個對Java或編程有廣泛了解的人,但任何幫助將不勝感激!
1 回答

慕的地6264312
TA貢獻1817條經驗 獲得超6個贊
在代碼中使用它,
sc.useDelimiter("[^A-Za-z]");
字母表以外的任何字符都將充當分隔符,因此也將充當分隔符,因此我建議將上面的代碼行更改為此,'
sc.useDelimiter("[^A-Za-z']");
因此將不再被視為分隔符,并應保留在單詞中。'
'
但我認為最好閱讀你的文本并使用適當的正則表達式來匹配和過濾你的單詞,所以,只有當它存在于單詞中而不是可能在單詞之外時,你才例外地允許a。'
添加回答
舉報
0/150
提交
取消