Java - 我有一个Scanner类和阅读文本文件的问题

时间:2016-11-18 22:44:33

标签: java java.util.scanner filereader

我的某个代码出了问题。它应该使用扫描仪方法来读取和打印文件上的数字(有500个数字,每行只有一个)。如果数字大于/等于或小于500,则必须进行过滤。它应该停在文件的末尾。但是,我的代码不能按预期工作,而while循环(包含hasNext())不会终止。你能帮助我找到一个让它起作用的答案,同时解释你的过程吗?我对java很新...我必须在没有数组的情况下这样做,这使得它更难......谢谢!这是代码:

//imports
import java.util.Scanner;
import java.io.*;


public class Prog209a {
    public static void main(String [] args) {

        //Declare file
        File file = new File("src/p209a.dat");

        //Declare variables
        int countLess = 0;
        int countMore = 0;
        long num;

        //try-catch statement for the absence of file
        try {

            //set the Scanner as reading the file
            Scanner scanData = new Scanner(file);

            while (scanData.hasNext()); {

                //num is number read in the file
                num = scanData.nextInt();

                //if the number is less than 500 countless is incremented+1
                if (num < 500) countLess++;

                //if other countMore is incremented+1
                else countMore++;
            }

            //print the following
            System.out.println("There are "+countLess+" numbers under 500!");
            System.out.println("There are "+countMore+" number greater than or equal to 500!");

            //if the file is not found
        } catch (FileNotFoundException e) {

            //Print the following
            System.out.println("The file does not exist! Please retry!");
        }
    }
}

0 个答案:

没有答案