【问题标题】:Getting an error - 'java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown' [duplicate]收到错误 - 'java:未报告的异常 java.io.FileNotFoundException;必须被抓住或宣布被抛出' [重复]
【发布时间】:2019-07-11 13:48:56
【问题描述】:

导入 java.util.; 导入 java.io.;

公共类主要{ public static void main(String args[]){

    int total = 0;

    File file = new File("expenditure.txt");
    Scanner fileScanner = new Scanner(file);

    while (fileScanner.hasNextLine()) {
        total += fileScanner.nextInt();
        }
        fileScanner.close();

    System.out.println("The total expenditure is " + total);
}

}

【问题讨论】:

标签: java file


【解决方案1】:

try-catch包围您对文件的阅读,示例代码如下:

import java.util.*;
import java.io.*;

public class Main {
    public static void main(String args[]){

        try {
            int total = 0;

            File file = new File("expenditure.txt");
            Scanner fileScanner = new Scanner(file);

            while (fileScanner.hasNextLine()) {
                total += fileScanner.nextInt();
            }
            fileScanner.close();

            System.out.println("The total expenditure is " + total);
        } catch (FileNotFoundException ex){
            System.out.println("File not found");
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多