Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

File read code caught in loop? Can't figure out the error <code below>

// Template Dialog.
import java.util.Scanner;
import java.io.*;
public class Read_Numeric
{
    public static void main(String[] args)throws IOException
    {
        double Sum = 0.0;
        double Num = 0.0;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter the name of the file: ");
        String filename = keyboard.nextLine();
        //Open File
        File file = new File(filename);
        Scanner inputFile = new Scanner(file);
        
        //Get input and perform
        while (inputFile.hasNext());
            {
                Num = inputFile.nextDouble();
                Sum = Sum + Num;
            }
        inputFile.close();
        System.out.println("The sum of the numbers is: "+ Sum);     
    }
}

I believe the code is somehow getting caught in the ‘while’ loop but have no idea what i’m doing wrong. Please help.

Input text would be file location: C:\Users\IanSP\Desktop\Java\Student.txt

Previous code has written a file in this exact location as it shows in the file location an can be opened physically to show written data.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

while (inputFile.hasNext()){
     Num = inputFile.nextDouble();
     Sum = Sum + Num;
}

this part should be this way, need to delete the mark after the while

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading