1

I have a problem on one of my codes. It is supposed to use the Scanner methods to read and print a number on a file (there are 500 numbers and only one per line). It has to filter if the number is greater/equal to or lesser than 500. It should stop at the end of the file. However, my code does not work as intended, and the while loop (which contains a hasNext()) does not terminate. Could you guys help me figure out an answer to make it work, while at the same time explaining your process? I am fairly new to java... I have to do it without an array, which makes it even harder...Thank you! Here is the code:

//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!");
        }
    }
}
PN.Perrin
  • 11
  • 1

0 Answers0