2015-10-28 18 views
-2

編寫一個程序,顯示一個構造函數將關於構造函數失敗的信息傳遞給異常處理程序。定義類SomeClass,它在構造函數中引發一個Exception。你的程序應該嘗試創建SomeClass類型的對象,並捕獲構造函數拋出的異常。Dietel 11.19如何添加前置和後置條件

如何爲此代碼添加前置和後置條件?

import java.util.Scanner; 

public class Demo3 { 


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

    SomeClass testException; 

    try 
    { 
     testException = new SomeClass(); 
    } 
    catch(Exception e) 
    { 
     System.out.println(); 
    } 
} 
} 

public class SomeClass{ 


    public SomeClass() throws Error { 
    throw new Exception(); 

    } 
} 
+0

你想添加什麼前置條件和後置條件? –

+0

我想添加一個前提條件,檢查輸入是否是正確的類型和返回布爾值的後期條件。因此,例如,輸入一定範圍內的輸入的前提條件,以及將返回true/false的後置條件。 – XYZandMe

+0

根據代碼和問題的第一段,這沒有任何意義。 *什麼*輸入?在構造函數中拋出異常的類的連接是什麼? –

回答

0

你應該能夠創建一個構造函數,它需要兩個參數並引發異常。此外,如果您想驗證某些值,則可以在程序中聲明一些前置和後置條件。我希望它有幫助。您的代碼可能如下所示:

public class Demo3 { 
    public static void main(String[] args){ 

    Scanner scan=new Scanner(System.in); 

    System.out.println("Enter the firstNumber:"); 

    int a=scan.nextInt(); 

    System.out.println("Enter the secondNumber:"); 

    int b=scan.nextInt(); 

//you can write some assertion here to meet the pre-conditions 
assert(b>0):"You cannot enter a number less or equal to zero"; 

SomeClass testException; 

try 
{ 
    testException = new SomeClass(a,b); 
} 
catch(Exception e) 
    { 
    System.out.println("Exception occurred:"+e.getMessage()); 
    } 
} 
} 

public class SomeClass{ 
    int firstNumber; 
    int secondNumber; 
    public SomeClass() { 

    } 
    public SomeClass (int firstName,int secondName) throws Exception { 
    //the message to show when you have getMessage() invoked 
    throw new Exception("Some exception occurrred"); 

    } 
} 
0

這的確幫助,謝謝!儘管我已經重寫了我的代碼,但是我不知道如何在遇到前置或後置條件時拋出異常。

如何在不滿足前提條件的情況下拋出異常,如InputMismatchException?

import java.util.Scanner; 

public class Demo3 { 
    public static void main(String[] args){ 

    Scanner scan=new Scanner(System.in); 

    System.out.println("Enter a number between 0 and 10:"); 

    int a=scan.nextInt(); 

    System.out.println("Enter another number between 0 and 10:"); 

    int b=scan.nextInt(); 

//assertion here to meet the pre-conditions 
    assert (a >= 0 && a <= 10) : "bad number: " + a; 
    assert (b >= 0 && b <= 10) : "bad number: " + b; 

SomeClass testException; 

try 
{ 
    testException = new SomeClass(a,b); 
} 
catch(Exception e) 
    { 
    System.out.println("Exception occurred: "+e.getMessage()); 
    } 

} 
} 

public class SomeClass{ 
    int a; 
    int b; 
    public SomeClass() { 

    } 
    public SomeClass (int a,int b) throws Exception { 

    throw new Exception("You've got an error!"); 

    } 
} 
相關問題