2

I know i'm doing something very wrong here, but I'll be frank here my knowledge of java is very weak. Whenever I call dataIn.readLine() I get this compile time error

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

Here's the code, I know the naming conventions are awful and that it nearly does nothing.

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 Compiled it here as well with the same result.

4

2 回答 2

6

Change this:

public static void main( String[]args ){

to:

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

To understand why you need to do this, read this: 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 回答