【问题标题】:Buffered Reader Throwing Exception缓冲阅读器抛出异常
【发布时间】:2020-10-24 00:05:49
【问题描述】:

我想打印 hello “t” 次。所以,我写了这段代码sn-p。


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

class Buff
{
    public static void main(String args[])
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int t = Integer.parseInt(br.readLine());
        while(t-->0)
            bw.write("hello");

    }
}

输出异常


Buff.java:11: error: unreported exception IOException; must be caught or declared to be thrown
                String t = br.readLine();
                                      ^
Buff.java:14: error: unreported exception IOException; must be caught or declared to be thrown
                        bw.write("hello");

请帮忙!!! PS:即使我抛出 IOException 也无济于事

【问题讨论】:

  • "PS : 即使我放了 throws IOException 也无济于事" – 你把这个 throws 放在哪里了?因为public static void main(String args[]) throws IOException {...} 应该适合你。

标签: java loops bufferedreader ioexception bufferedwriter


【解决方案1】:

您必须捕获可能的异常(在本例中为 IOException)。

基本语法如下所示:

try {
    //Your code here
}
catch(IOException e) {
    //What do you want to do when something went wrong?
}

在您的情况下,以下代码将起作用:

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

class Buff
{
    public static void main(String args[])
    {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
            
            int t = Integer.parseInt(br.readLine());

            //Closing Readers and Writers when not needed anymore is good-practice
            br.close();

            //"-->" wasn't working for me in this case
            while(t > 0) {
                bw.write("hello\n");
                t--;
            }
            bw.flush();
            bw.close();
        }

        //Catching possible exceptions
        catch(IOException e) {
            e.printStackTrace();
        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 2018-05-19
    相关资源
    最近更新 更多