从文本文件中添加并忽略语法错误

时间:2016-11-30 15:51:39

标签: java

我正在编写一个代码,用于汇总文本文件中的数字并显示总数。但是我想这样做,如果用户输入一个单词或一个十进制数字然后忽略它并继续加上下一个数字?

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

    }
}

2 个答案:

答案 0 :(得分: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)

改为使用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);