[英]Incorrectly passing token to string array
我正在編寫一個程序,該程序讀取作為參數傳遞給main方法的文本文件,並從文件中提取所有唯一的單詞,並在控制台中每行打印一個單詞。 從掃描儀讀取每一行時,我無法將令牌傳遞給字符串數組:
我認為有幾處錯誤或可以更有效的方式編寫:
1)令牌已初始化為100。這是一個明顯的約束,我考慮過使用諸如arrayList或vector之類的動態數組,但最終決定使用簡單的字符串數組並簡單地擴展該數組(即,創建一個新數組,其大小是原始數組,方法是編寫某種類型的條件語句,該條件語句將確定令牌是否已被max個元素填充,但掃描程序仍有更多行。
2)我不確定在for循環中簡單地將input.hasNextLine()
作為測試語句傳遞input.hasNextLine()
有意義。 我基本上想循環,只要輸入達到EOF
3)我希望正則表達式中的表達式能夠捕獲所有標點符號,空格和數字,但我不確定它是否正確編寫,而且不能100%確定
4)有問題的行是tokens[index] = token[index]
,我不確定這是正確的。 我希望將每行中的標記添加到標記中。
public static void main(String[] arg) throws FileNotFoundException {
File textFile = new File(arg[0]);
String[] tokens = new String[100];
try {
Scanner input = new Scanner(textFile);
for (int index = 0; input.hasNextLine(); index++) {
String[] token = input.nextLine().split("[.,;']+\\d +\\s");
tokens[index] = token[index];
}
for (String token : tokens) {
System.out.println(token);
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
代碼中有幾個錯誤,我將嘗試涵蓋所有這些錯誤:
正則表達式實際上是特定於令牌之間的內容(標點符號+一個數字+空格+其他空格)
public static void main(String[] arg) throws FileNotFoundException { File textFile = new File(arg[0]); ArrayList<String> tokens = new ArrayList<String>(); try { Scanner input = new Scanner(textFile); while (input.hasNextLine()) { String[] lineTokens = input.nextLine().split("[,;:\\"\\\\.\\\\s]+"); for (String token : lineTokens) { tokens.add(token); } } for (String token : tokens) { System.out.println(token); } input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } }
正則表達式可以改進,但是無論如何它都取決於您的數據,因此我不知道您需要處理的所有情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.