2016-11-30 80 views
1

我正在編寫一個代碼,它將文本文件中的數字相加並顯示總數。但是我想這樣做,如果用戶輸入一個單詞或一個十進制數字,那麼它會忽略它並繼續累加下一個數字?從文本文件添加並忽略語法錯誤

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class Task1 { 
    public static void main(String [] args) throws FileNotFoundException { 
     File myFile = new File("Numbers.txt");   
     Scanner scan = new Scanner(myFile); 

     int sum=0;   

     while (scan.hasNext()) {   
      sum+= scan.nextInt();  
     } 
     System.out.println(sum); 

     scan.close(); 

    } 
} 

回答

0
import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.Scanner; 

public class Task1 { 
    public static void main(String [] args) throws FileNotFoundException { 
     File myFile = new File("Numbers.txt");   
     Scanner scan = new Scanner(myFile); 

     String sum="";   
     int number = 0; 
     int total = 0; 
     while (scan.hasNext()) { 
      try { 
       sum = scan.next(); 
       number = Integer.parseInt(sum);   
       total += number; 
      } catch(Exception e) { 
       System.out.println("Unable to parse string !! + " + sum); 
      } 
     } 
     System.out.println("The total is : " + total); 

     scan.close(); 

    } 
} 
+1

它不順心的「字符串總和= 0; ' –

+0

哦,是的,這是一個錯誤,編輯回答,謝謝 –

0

使用scan.next(),而是和環繞它Integer.parseInt()。然後添加一個try-catch趕上將發生NumberFormatException■如果Integer.parseInt()試圖解析一個非整數

while (scan.hasNext()) { 
    try { 
     sum += Integer.parseInt(scan.next()); 
    } 
    catch (NumberFormatException e) { 
     //If there was a NumberFormatException, do nothing. 
    } 
} 
System.out.println(sum);