有理数类的设计
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?
适合