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 に答える