Question

Can anybody tell my why this programme does not work.You should create a file that contines double values.When I run the programme the it reads the file but does not display the sum.

import java.util.*;
import java.io.*;
public class TheGradesArrays
{
public static void main(String [] args)
{
    Scanner scan = new Scanner (System.in);
    Scanner infile=null;
    boolean isValid;
    String name;
    do
    {
        isValid=true;
        System.out.print("Enter the name of the file: ");
        name=scan.nextLine();
        try
        {       
            infile = new Scanner (new FileInputStream (name+".txt"));
        }
        catch(IOException fe)
        {
            System.out.println("The name is not valid! Renter the name."+fe);
            fe.printStackTrace();
            isValid=false;

        }
    }while(! isValid );

    double sum=0,grade;
    while(infile.hasNextDouble());
    {
        grade=infile.nextDouble();
        sum+=grade;
    }

    System.out.print("The Sum = "+sum);

}
}
Was it helpful?

Solution

Change the infinite loop

while(infile.hasNextDouble());

into a correct loop header:

while(infile.hasNextDouble())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top