2014-04-01 78 views
0

有人可以告訴我爲什麼這個程序不起作用。你應該創建一個文件,以控制double值。當我運行該程序時,它讀取文件但不顯示總和。該程序不讀取文件

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

} 
} 

回答

5

變化的無限循環

while(infile.hasNextDouble()); 

到一個正確的環頭:

while(infile.hasNextDouble()) 
+0

謝謝你,我沒注意到! – user3485080