[英]Getting scanner to read text file
我正在尝试使用扫描仪读取使用JFileChooser
拉出的文本文件。 wordCount
工作正常,所以我知道它正在读取。 但是,我无法搜索用户输入的单词的实例。
public static void main(String[] args) throws FileNotFoundException {
String input = JOptionPane.showInputDialog("Enter a word");
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
File fileSelection = fileChooser.getSelectedFile();
int wordCount = 0;
int inputCount = 0;
Scanner s = new Scanner (fileSelection);
while (s.hasNext()) {
String word = s.next();
if (word.equals(input)) {
inputCount++;
}
wordCount++;
}
如果用户输入的文本大小写不同,则应尝试使用equalsIgnoreCase()
除了blackpanthers答案,您还应该使用trim()来解决空白问题。as“ abc”不等于“ abc”
您必须寻找
,; 。 ! ? 等等
每个字。 next()
方法将捕获整个字符串,直到遇到empty space
为止。
它将考虑“嗨,你好吗?” 如以下“嗨”,“如何”,“是”,“您”?
您可以使用方法indexOf(String)
查找这些字符。 您还可以使用replaceAll(String regex,String replacement)替换字符。 您可以个性化地删除每个字符,也可以使用Regex
,但是这些字符通常更难于理解。
//this will remove a certain character with a blank space
word = word.replaceAll(".","");
word = word.replaceAll(",","");
word = word.replaceAll("!","");
//etc.
阅读有关此方法的更多信息:
这是一个正则表达式示例:
//NOTE: This example will not work for you. It's just a simple example for seeing a Regex.
//Removes whitespace between a word character and . or ,
String pattern = "(\\w)(\\s+)([\\.,])";
word = word.replaceAll(pattern, "$1$3");
资源:
http://www.vogella.com/articles/JavaRegularExpressions/article.html
这是一个很好的Regex示例,可以为您提供帮助:
您应该看一下matches()
。
equals
不会对您有所帮助,因为next()
不会逐字返回文件,而是将空格( 不是逗号,分号等)逐个标记(如其他提到的)分隔开。
这是java文档
String#matches(java.lang.String)
...还有一个小例子。
input = ".*" + input + ".*";
...
boolean foundWord = word.matches(input)
.
是正则表达式通配符,代表任何符号。 .*
代表0个或多个未定义符号。 如果输入在word
某处,那么您将获得匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.