小编FAU*_*HID的帖子

Java异常处理?

以下代码计算存储在文本文件中的数字的平均值.我为"找不到文件"错误添加了一些异常处理.我需要知道如何在文本文件中的数据不是数字(或非int)时添加另一个异常.我考虑过添加多个捕获量.不知道怎么样?

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

public class NumAvg2 {

    public static void main(String[] args)
    {
    int c = 1;  
    long sum = 0;
    String strFileName;

    strFileName = args[0];

    Scanner scFileData;
    try{
        scFileData = new Scanner (new File(strFileName));

        while (scFileData.hasNext())
        {
            sum = sum + scFileData.nextInt();
            c++;
        }

    scFileData.close();
    System.out.println("Number of integers: " + (c - 1)); 
    System.out.println( "Average = " + (float)sum/(c - 1));

    } catch (FileNotFoundException e) {
        System.out.println("File not found!");
        System.exit(1);
    }

  } 
}   
Run Code Online (Sandbox Code Playgroud)

java exception-handling exception try-catch

3
推荐指数
1
解决办法
2589
查看次数

标签 统计

exception ×1

exception-handling ×1

java ×1

try-catch ×1