【问题标题】:Counting strings via Scanner通过扫描仪计数字符串
【发布时间】:2013-10-13 19:08:15
【问题描述】:

我创建了一个简单的扫描器来计算 .txt 文件中的字符串数。每个字符串都在 nextLine。它算错了,每次它给我的数字是 297,即使有超过 20 000 个字符串。 .txt 文件是由我编写的另一个程序创建的,它从网站获取链接并将它们与 FileWriter 和 BufferedWriter 一起保存到 .txt 文件中。有什么问题?

public class Counter {

public static void main(String[] args) throws FileNotFoundException {

    Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
    String string = scanner.next();
    int count = 0;

    while (scanner.hasNextLine()) {
        string = scanner.next();
        count++;
        System.out.println(count);
    }           
 }
}

编辑:字符串示例:

yahoo.com
google.com
etc.

【问题讨论】:

  • "超过 20 000 个字符串" 你确定超过 20000 行吗?
  • 链接之类的字符串。是的,我确定 - 我已经在 MS Word 中数过了。
  • 尝试使用scanner.hasNext() 看看会发生什么。
  • 看起来不太好的一件事是,当您声明String string 时,您正在阅读scanner.next(); 并且不计算它。另一件事是,如果你想计算有多少行,你应该使用nextLine,而不是next
  • 你不需要String string = scanner.next,只需要String string;

标签: java java.util.scanner


【解决方案1】:

试试这个来测试最后一个字符串是什么:

public class Counter {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
        int count = 0;

        String string;
        while (scanner.hasNextLine()) {
            string = scanner.nextLine();
            count++;
        }
        System.out.println(string);
        System.out.println(count);  
   }
}

【讨论】:

  • 你怎么知道文本文件中有 20k 个项目?它们是否按照您发布的方式以垂直顺序列出?
  • 是的,按照我发布的垂直顺序。我已经在 MS Word 和我的其他程序中计算过它们,因为它们保存在 HashSet 中。 HashSet.size().
【解决方案2】:

试试这个,使用nextLine,解析会更准确

public class Counter {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
        String string = scanner.next();
        int count = 0;

        while (scanner.hasNextLine()) {
            string = scanner.nextLine();
            count += string.split(" ").length;
            System.out.println(count);
        }           
     }
    }

【讨论】:

  • 可能没有。也许您使用的字符串与您想象的不同。可能这种方法不适合读取文件,我没见过用Scanner。
【解决方案3】:

试试这个:

public class Counter {

public static void main(String[] args) throws FileNotFoundException {

    Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
    int count = 0;

    while (scanner.hasNextLine()) {
        scanner.nextLine();
        count++;
        System.out.println(count);
    }           
 }
}

您对此有何回答?

【讨论】:

  • 太棒了,现在你计算的是 ROWS 而不是字符串,甚至 5 分钟后我用 nextLine 发布了解决方案...
【解决方案4】:

默认情况下,扫描仪使用空白分隔符,但在这种情况下,您希望将 \n 字符作为分隔符,对吗?您可以为此使用Scanner.useDelimiter("\n");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多