readline中的java编译时错误

Vor*_*ato 2 java ioexception bufferedreader

我知道我在这里做了一些非常错误的事情,但我会坦白地说,我对java的了解非常薄弱.每当我调用dataIn.readLine()时,我都会收到此编译时错误

unreported exception java.io.IOException; must be caught or declared to be thrown
Run Code Online (Sandbox Code Playgroud)

这是代码,我知道命名约定很糟糕,它几乎什么都不做.

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 ); 

    }
}
Run Code Online (Sandbox Code Playgroud)

http://www.ideone.com/9OM6O此处也编译了相同的结果.

Mar*_*ope 6

改变这个:

public static void main( String[]args ){
Run Code Online (Sandbox Code Playgroud)

至:

public static void main( String[]args ) throws IOException {
Run Code Online (Sandbox Code Playgroud)

要了解您需要执行此操作的原因,请阅读以下内容:http://download.oracle.com/javase/tutorial/essential/exceptions/


Dou*_*oug 5

readLine() 可能会抛出 IOException。您需要将其包装在一个 try-catch 块中,该块在出现异常时捕获该异常,然后以适合您正在执行的操作的方式处理它。如果 readLine() 抛出异常,控制将立即流出 try 块并进入 catch 块。

try
{
    dataIn.readLine();
    // ... etc
}
catch(IOException e)
{
    // handle it. Display an error message to the user?
}
Run Code Online (Sandbox Code Playgroud)