2

私はここで非常に間違ったことをしていることを知っていますが、率直に言って、Javaに関する私の知識は非常に弱いです。dataIn.readLine()を呼び出すたびに、このコンパイル時エラーが発生します

unreported exception java.io.IOException; must be caught or declared to be thrown

これがコードです。命名規則がひどく、ほとんど何もしないことを私は知っています。

import java.io.*; 
public class money {
    public static void main( String[]args ){
        String quarters; 
        String dimes; 
        String nickels; 
        String pennies; 
        int iquarters; 
        int idimes;
        int inickels; 
        int ipennies; 
        BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in)); 

        System.out.println( "Enter the number of quarters. " ); 
        quarters = dataIn.readLine(); 
        System.out.println( "Enter the number of dimes" ); 
        dimes = dataIn.readLine(); 
        System.out.println( "Enter the number of nickels" ); 
        nickels = dataIn.readLine(); 
        System.out.println( "Enter the number of pennies" ); 
        pennies = dataIn.readLine(); 

        iquarters = Integer.parseInt( quarters ); 
        idimes = Integer.parseInt( dimes ); 
        inickels = Integer.parseInt( nickels ); 
        ipennies = Integer.parseInt( pennies ); 

    }
}

http://www.ideone.com/9OM6Oここでも同じ結果でコンパイルしました。

4

2 に答える 2

6

これを変える:

public static void main( String[]args ){

に:

public static void main( String[]args ) throws IOException {

これを行う必要がある理由を理解するには、次をお読みください:http: //download.oracle.com/javase/tutorial/essential/exceptions/

于 2011-05-01T01:26:53.837 に答える
4

readLine()はIOExceptionをスローできます。例外が発生した場合にその例外をキャッチするtry-catchブロックでラップし、実行していることに対して適切な方法で処理する必要があります。readLine()によって例外がスローされた場合、制御はすぐにtryブロックからcatchブロックに流れます。

try
{
    dataIn.readLine();
    // ... etc
}
catch(IOException e)
{
    // handle it. Display an error message to the user?
}
于 2011-05-01T01:27:37.280 に答える