classSimpleCompute{//相加publicintadd(Stringi,Stringj)throwsNumberFormatException{returnInteger.parseInt(i)+Integer.parseInt(j);//傳回和}//計算除ARithemeticException為抛出...
class SimpleCompute
{ //相加
public int add(String i,String j) throws NumberFormatException
{
return Integer.parseInt(i)+Integer.parseInt(j);
//傳回和
}
//計算除 ARithemeticException為抛出異常類型
public int div(String i,String j) throws ArithmeticException
{
return Integer.parseInt(i)/Integer.parseInt(j);//傳回商
} //計算減
public int subtract(String i,String j) throws NumberFormatException
{
return Integer.parseInt(i)-Integer.parseInt(j); //傳回差
} //計算乘 NumberFormatException為抛出異常類型
public int Multiply(String i,String j) throws NumberFormatException
{
return Integer.parseInt(i)*Integer.parseInt(j);//傳回積
}
}
public class ThrowsException //抛出異常類
{
public static void main(String args[])
{
SimpleCompute sc=new SimpleCompute();
try{
String num1="12";
String num2="1";
System.out.println("兩數之和是:"+sc.add(num1,num2));
System.out.println("兩數之差是:"+sc.subtract(num1,num2));
System.out.println("兩數之商是:"+sc.div(num1,num2));
System.out.println("兩數之積是:"+sc.Multiply(num1,num2));
}
catch (NumberFormatException e)
{
System.out.println("輸入資料有誤");
}
catch (ArithmeticException e)
{
System.out.println("除數為0,請重新輸入");
}
finally {
System.out.println("程式運作結束");
}
}
}
展開