xiaojie wgjj XML中的DTD文件型別定義完全解析
阿新 • • 發佈:2020-10-04
1.有理數類的程式碼
import java.util.Scanner; public class Rational { private int numberator=0; private int denominator=1; public Rational() { this(0,1); } public Rational(int numberator,int denominator) { if (numberator == 0) { this.numberator = numberator; this.denominator = denominator; } else { int com = maxCom(Math.abs(numberator), Math.abs(denominator));//求最大公約數 if (denominator < 0) { numberator = -numberator; denominator = -denominator; } this.numberator = numberator / com; this.denominator = denominator / com; } } private int maxCom(int a, int b) { // 求最大公約數 if (a < b) { int c = a; a = b; b = c; } int r = 0; try { r = a % b; } catch (Exception e) { System.out.println(e.getMessage()); } // 分母為零時異常處理 while (r != 0) { a = b; b = r; r = a % b; } return b; } public Rational add(int numberator,int denominator) { int d = denominator; denominator = this.denominator * denominator; numberator = this.numberator * d + numberator * this.denominator; return new Rational(numberator, denominator); } public Rational sub(int numberator, int denominator) {// 減 int d = denominator; denominator = this.denominator * denominator; numberator = this.numberator * d - numberator * this.denominator; return new Rational(numberator, denominator); } public Rational mul(int numberator, int denominator) {// 乘 denominator = this.denominator * denominator; numberator = this.numberator * numberator; return new Rational(numberator, denominator); } public FractionalNumber div(int numberator, int denominator) {// 除 int d = denominator; denominator = this.denominator * numberator; numberator = this.numberator * d; return new FractionalNumber(numberator, denominator); } public String toString() { return numberator + "/" + denominator; }
2.測試程式碼
public static void main (String[] args) { { System.out.println("請輸入要計算的表示式:"); Scanner sc=new Scanner(System.in); String str=sc.next(); int a=Integer.parseInt(str.charAt(0)+"");//分子 int b=Integer.parseInt(str.charAt(2)+"");//分母 int c=Integer.parseInt(str.charAt(4)+""); int d=Integer.parseInt(str.charAt(6)+""); Rational num=new Rational(a,b); switch(str.charAt(3)) { case'+':System.out.println("加法"); System.out.println(num.add(c,d).toString()); //break;測試程式碼 case'-':System.out.println("減法"); System.out.println(num.sub(c,d).toString()); //break; case'*':System.out.println("乘法"); System.out.println(num.mul(c,d).toString()); //break; case'/':System.out.println("除法"); System.out.println(num.div(c,d).toString()); //break; } }} }
3.嘗試描述怎麼與c語言的有理數程式碼相比較,為什麼你設計的類更加面向物件?
c語言的有理數程式碼,我會傾向於從過程考慮,考慮要寫怎樣的函式來用它,而不是考慮它應該會有怎樣的方法.
4.嘗試從程式碼複用的角度來描述你設計的有理數類。從幾個方面討論。
a.別人如何複用你的程式碼?
匯入我書寫的類的包,就可以使用我寫的類和方法
b.別人的程式碼是否依賴你的有理數類的屬性?當你的有理數類的屬性修改時,是否會影響他人呼叫你有理數類的程式碼?
依賴,我的有理數類的為private,所以不會影響他人呼叫我的有理數程式碼
c.有理數類的public方法是否設定合適?為什麼有的方法設定為private?
適合