Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readline in java compile time error

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.

like image 391
VoronoiPotato Avatar asked Jul 16 '26 11:07

VoronoiPotato


2 Answers

readLine() can throw an IOException. You need to wrap it in a try-catch block that catches that exception if it arises, and then handles it in a way that's sane for what you're doing. Control will immediately flow out of the try block and into the catch block if an exception is thrown by readLine().

try
{
    dataIn.readLine();
    // ... etc
}
catch(IOException e)
{
    // handle it. Display an error message to the user?
}
like image 190
Owen Avatar answered Jul 18 '26 02:07

Owen


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/

like image 38
Mark Pope Avatar answered Jul 18 '26 00:07

Mark Pope



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!