Java代码报错未捕获IOException,求排查子数组求和代码问题
问题描述
给定整数数组,处理形如[i, j]的查询:输出数组中从A[i]到A[j](包含两端)的元素之和。编写的Java代码运行时报错:unreported exception IOException; must be caught or declared to be thrown at bw.write(s);,代码如下:
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc=new Scanner(System.in); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); int n=sc.nextInt(); long arr[]=new long[n]; for(int i=0;i<n;i++) arr[i]=sc.nextLong(); long farr[]=new long[n]; farr[0]=arr[0]; for(int i=1;i<n;i++) farr[i]=farr[i-1]+arr[i]; int q=sc.nextInt(); while(q-->0){ int i=sc.nextInt(); int j=sc.nextInt(); if(i!=0){ //I'm converting long value to String bcoz bw can't write long value in buffer String s=String.valueOf(farr[j]-farr[i-1]); bw.write(s); } else{ String s=String.valueOf(farr[j]); bw.write(s); } } bw.flush(); bw.close(); } }
错误原因
BufferedWriter的write()、flush()、close()方法都会抛出IOException,这是Java的受检异常,要求必须显式处理:要么用try-catch块捕获异常,要么在方法签名上声明throws IOException。当前main方法既没有捕获异常,也没有声明抛出,因此编译报错。
另外原代码存在一个逻辑小问题:多个查询的输出结果会连在一起,没有换行,不符合常规输出格式。
修复方案
提供两种可行的修复方式,推荐第二种(try-with-resources),因为它能自动管理流资源,避免手动关闭遗漏导致的资源泄漏:
方式1:在main方法上声明抛出IOException
直接修改main方法签名,添加throws IOException,同时在每次写入后添加换行:
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); int n=sc.nextInt(); long arr[]=new long[n]; for(int i=0;i<n;i++) arr[i]=sc.nextLong(); long farr[]=new long[n]; farr[0]=arr[0]; for(int i=1;i<n;i++) farr[i]=farr[i-1]+arr[i]; int q=sc.nextInt(); while(q-->0){ int i=sc.nextInt(); int j=sc.nextInt(); String s; if(i!=0){ s=String.valueOf(farr[j]-farr[i-1]); } else{ s=String.valueOf(farr[j]); } bw.write(s); bw.newLine(); // 添加换行,分隔不同查询结果 } bw.flush(); bw.close(); sc.close(); // 关闭Scanner资源 } }
方式2:使用try-with-resources自动管理资源(推荐)
try-with-resources会在代码块结束后自动关闭实现了AutoCloseable接口的资源,无需手动调用close(),同时用try-catch捕获异常:
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { try (Scanner sc = new Scanner(System.in); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out))) { int n = sc.nextInt(); long arr[] = new long[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextLong(); long farr[] = new long[n]; farr[0] = arr[0]; for (int i = 1; i < n; i++) farr[i] = farr[i - 1] + arr[i]; int q = sc.nextInt(); while (q-- > 0) { int i = sc.nextInt(); int j = sc.nextInt(); String s; if (i != 0) { s = String.valueOf(farr[j] - farr[i - 1]); } else { s = String.valueOf(farr[j]); } bw.write(s); bw.newLine(); // 添加换行 } bw.flush(); } catch (IOException e) { e.printStackTrace(); // 异常处理,可根据需求调整 } } }
内容的提问来源于stack exchange,提问作者Charan Guvvala
相关产品推荐
相关产品推荐

