通过扫描仪计数字符串

时间:2013-10-13 19:08:15

标签: java java.util.scanner

我创建了一个简单的扫描程序来计算.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.

4 个答案:

答案 0 :(得分:0)

试试这个,使用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);
        }           
     }
    }

答案 1 :(得分:0)

试试这个:

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);
    }           
 }
}

你对此有何回答?

答案 2 :(得分:0)

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

答案 3 :(得分:0)

尝试此操作来测试最后一个字符串是什么:

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);  
   }
}