2013-03-05 20 views
1

我的程序的目標是要求用戶輸入一個數字,然後使用創建的自定義方法來平方和輸出平方。但是,嘗試這個時出現問題。請注意,這是我利用用戶輸入方法(在他們完整的初學者)正方形數學方法不起作用(默認構造函數不能處理異常類型)

錯誤代碼,第一個節目

Error: Default constructor cannot handle exception type java.io.IOException thrown by implicit super constructor. Must define an explicit constructor

代碼:

import java.io.*; 

public class Squareit 
{ 
    BufferedReader myInput=new BufferedReader(new InputStreamReader(System.in)); 
    { 
     String input; 
     int num; 
     System.out.println("1-12"); 
     input = myInput.readLine(); 
     num = Integer.parseInt(input); 
    } 

    public void square(int num) 
    { 
     int ans = (num * num); 
     System.out.println(" is" + ans); 
    } 

    public static void main(String[] args) throws IOException 
    { 
     Squareit t = new Squareit(); 
     t.square(0); 
    } 
} 
+0

您可能希望別人能夠正確理解你的問題 – Sujay 2013-03-05 22:41:53

+0

對不起格式化你的代碼中,我似乎總是有麻煩正確格式化。 – user2133068 2013-03-05 22:43:48

+0

底部的那兩個空塊是什麼? – 2013-03-05 22:43:58

回答

1

初始化代碼是問題。

BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in)); 
{ 
    String input; 
    int num; 
    System.out.println("1-12"); 
    input = myInput.readLine(); 
    num = Integer.parseInt (input); 
} 

您應該改爲創建構造函數。

class SquareIt { 
    BufferedReader myInput; 
    String input; 
    int num; 
    public SquareIt() throws IOException, NumberFormatException { 
     myInput = new BufferedReader (new InputStreamReader (System.in)); 
     System.out.println("1-12"); 
     input = myInput.readLine(); 
     num = Integer.parseInt (input); 
    } .... 
+0

請注意'NumberFormatException'未被檢查 – 2013-03-05 22:49:14

+0

它表示該方法的返回類型丟失 – user2133068 2013-03-05 22:50:43

+0

@ user2133068應該沒有構造函數的返回類型。也許你錯了構造函數名和類名? – 2013-03-05 22:51:59

3

移動這個整個塊成構造不作爲隱式超級構造函數。

private int num; 
public SquareIt() throws IOException, NumberFormatException { 
    BufferedReader myInput=new BufferedReader (new InputStreamReader (System.in)); 
    String input; 
    System.out.println("1-12"); 
    input = myInput.readLine(); 
    num = Integer.parseInt (input); 
} 
+2

我相信你仍然需要趕上或拋出'IOException' – 2013-03-05 22:47:34

+0

對不起,這是絕對正確 – 2013-03-05 22:48:10

+1

我相信主將是一個更合適的地方有用戶輸入(創建緩衝讀取器),它會給予更多的靈活性 – Ron 2013-03-05 22:49:24

1

您正在構造BufferedReader並從構造函數外讀取它,並且這可能會引發IOException。你必須把這個指令到構造函數,並宣佈在其異常從而處理這個異常throws子句:

BufferedReader myInput; 

public SquareIt() throws IOExcption { 
    myInput = new BufferedReader (new InputStreamReader (System.in)); 
    String input; 
    int num; 
    System.out.println("1-12"); 
    input = myInput.readLine(); 
    num = Integer.parseInt (input); 
} 

注意,這是一個很好的習慣,當你需要它只是聲明一個變量,並對其進行初始化立刻:

public SquareIt() throws IOExcption { 
    myInput = new BufferedReader(new InputStreamReader(System.in)); 
    System.out.println("1-12"); 
    String input = myInput.readLine(); 
    int num = Integer.parseInt (input); 
} 
相關問題