0

I've created a simple scanner to count the number of strings in a .txt file. Each string is at nextLine. It counts wrong, every time it gives me the number 297, even there're more than 20 000 strings. The .txt file was created by another program I've coded, it takes links from websites and saves them with FileWriter and BufferedWriter into the .txt file. What could be wrong?

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

Edit: example of strings:

yahoo.com
google.com
etc.
4

4 回答 4

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

您对此有何回答?

于 2013-10-13T19:15:55.497 回答
0

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

于 2013-10-13T19:16:39.210 回答
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);
        }           
     }
    }
于 2013-10-13T19:10:55.757 回答
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);  
   }
}
于 2013-10-13T19:27:46.287 回答