【问题标题】:Getting scanner to read text file让扫描仪读取文本文件
【发布时间】:2013-09-26 17:58:34
【问题描述】:

我正在尝试使用扫描仪读取使用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++;
}

【问题讨论】:

  • 给我们一个你的文件内容和输入的例子。
  • 如何显示 inputCount?你会在某些 GUI 上更新它吗?
  • 让它打印到控制台。我想可能是因为这个词后面跟着一个句号。

标签: java


【解决方案1】:

你必须寻找

, ; . ! ?等等

对于每个单词。 next() 方法抓取整个字符串,直到它遇到empty space

它会考虑“嗨,你好吗?”如下面的“hi”、“how”、“are”、“you?”。

您可以使用方法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.

阅读有关此方法的更多信息:

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29

这是一个正则表达式示例:

//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 for special characters in java

Parse and remove special characters in java regex

Remove all non-"word characters" from a String in Java, leaving accented characters?

【讨论】:

  • 有没有办法让扫描仪忽略该标点符号?
  • 我认为我提供的方法更全面,因为.* 接受了所有内容。 replaceAll 方法会遇到未指定的特殊符号的问题。在这种特殊情况下; 或一些外国标志。
  • 这种方法可以让用户自定义他/她想要删除的字符。
【解决方案2】:

如果用户输入的文字不同,那么你应该尝试使用equalsIgnoreCase()

【讨论】:

  • 我想可能是因为这个词后面跟着一个句号。有没有办法消除它?
【解决方案3】:

除了 blackpanthers 的回答之外,您还应该使用 trim() 来解释 whitespaces.as “abc”不等于“abc”

【讨论】:

    【解决方案4】:

    你应该看看matches()

    equals 不会帮助你,因为next() 不会逐字返回文件, 而是用空格(不是逗号、分号等)逐个标记分隔(正如其他人提到的那样)。

    这里是 java 文档
    String#matches(java.lang.String)

    ...还有一个小例子。

    input = ".*" + input + ".*";
    ...
    boolean foundWord = word.matches(input)
    

    . 是正则表达式通配符,代表任何符号。 .* 代表 0 个或多个未定义符号。因此,如果输入位于 word 中的某处,您将得到匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 2013-12-04
      • 1970-01-01
      相关资源
      最近更新 更多