1 public class Homework06 { 2 //編寫一個 main 方法 3 public static void main(String[] args) { 4 5 Cale cale = new Cale(2,10); 6 System.out.println("和=" + cale.sum()); 7 System.out.println("差=" + cale.minus()); 8 System.out.println("乘=" + cale.mul()); 9 Double divRes = cale.div(); 10 if(divRes != null){ 11 System.out.println("除=" + divRes); 12 } 13 14 } 15 } 16 /* 17 程式設計建立一個Cale計算類,在其中定義2個變數表示兩個運算元, 18 定義四個方法實現求和、差、乘、商(要求除數為0的話,要提示)並建立兩個物件,分別測試 19 */ 20 class Cale{ 21 double num1; 22 double num2; 23 public Cale(double num1,double num2){ 24 this.num1 = num1; 25 this.num2 = num2; 26 } 27 //和 28 public double sum(){ 29 return num1 + num2; 30 } 31 //差 32 public double minus(){ 33 return num1 - num2; 34 } 35 //乘積 36 public Double div(){ 37 //判斷 38 if(num2 == 0){ 39 System.out.println("num2 不能為0"); 40 return null; 41 }else{ 42 return num1 / num2; 43 } 44 } 45 }