我正在编写一个程序,该程序读取作为参数传递给 main 方法的文本文件,并从文件中提取所有唯一的单词,并将它们每行打印在控制台中。当从扫描仪读取每一行时,我无法将 token 传递到字符串数组:
我发现有几件事是错误的,或者可以用更有效的方式编写:
1)tokens 被初始化为 100。这是一个明显的限制,我考虑过使用像 arrayList 或 vector 这样的动态数组,但最终决定使用简单的字符串数组并简单地扩展数组(即创建一个新数组,将原始数组的大小,通过编写某种类型的条件语句来确定标记是否已填充最大元素,但扫描仪仍有更多行。
2)我不确定简单地传递 input.hasNextLine()
作为 for 循环中的测试语句是否有意义。我基本上想要循环,只要输入达到 EOF
3) 我希望 split 中的正则表达式能够捕获所有标点符号、空格和数字,我不能 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();
}
}
最佳答案
代码中有几个错误,我会尝试涵盖所有错误:
- 将 token 更改为 ArrayList,没有理由不这样做
- 您需要两次迭代:a) 文件中的行和 b) 行中的标记
正则表达式确实特定于标记之间的内容(标点符号 + 一位数字 + 空格 + 其他空格)
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(); } }
正则表达式可以改进,但无论如何它取决于您的数据,所以我无法知道您需要处理的所有情况。
关于java - 错误地将 token 传递给字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29381695/