1

您好,我正在尝试运行一些 java,但是我不断收到一条错误消息,这是消息: unreported exception IOException; must be caught or declared to be thrown myName = in.readLine();

    import java.io.*;
public class While{
    public static void main(String []args){
        int num = 0;
        while (num != 999){
            System.out.println("Enter a number:");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            num = Integer.parseInt(in.readLine());
            System.out.println("You typed: " + num);
        }
        System.out.println("999 entered, so the loop has ended.");
    }
}

直截了当,我没有使用过 java,这是我第一次使用它,我的老板问我是否可以看一下到目前为止,我已经能够做所有事情但我无法修复此错误消息,欢迎任何和所有帮助。

4

1 回答 1

7

try-catch语句包围代码并将BufferedReader初始化移到while循环之前。此外,请确保在使用资源后始终关闭它们。

public static void main(String []args) {
    int num = 0;
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(System.in));
        while (num != 999){
            System.out.println("Enter a number:");
            num = Integer.parseInt(in.readLine());
            System.out.println("You typed: " + num);
        }
    } catch (Exception e) {
        //handle your exception, probably with a message
        //showing a basic example
        System.out.println("Error while reading the data.");
        e.printStacktrace(System.in);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                System.out.println("Problem while closing the reader.");
                e.printStacktrace(System.in);
            }
        }
    }
    System.out.println("999 entered, so the loop has ended.");
}

如果您使用的是 Java 7,那么您可以使用try with resources语句来利用所有代码:

public static void main(String []args) {
    int num = 0;
    try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in))) {
        while (num != 999){
            System.out.println("Enter a number:");
            num = Integer.parseInt(in.readLine());
            System.out.println("You typed: " + num);
        }
    } catch (Exception e) {
        //handle your exception, probably with a message
        //showing a basic example
        System.out.println("Error while reading the data.");
        e.printStacktrace(System.in);
    }
    System.out.println("999 entered, so the loop has ended.");
}
于 2013-06-19T14:48:42.327 回答