本帖最后由 罗宝 于 2012-11-11 10:17 编辑
这样修改一下,就两个都能打印出来了!- public class Main {
- public static void main(String[] args) {
- try {
-
- FenShu fs1=new FenShu(4,0);
- FenShu fs2=new FenShu(5,0);
- FenShu result=fs1.cheng(fs2);
- String s=result.getString();
- System.out.println("乘运算后="+s);
- FenShu result1=fs1.chu(fs2);
- String s1=result1.getString();
- System.out.println("除法运算后="+s1);
- FenShu result2=fs1.jia(fs2);
- String s2=result2.getString();
- System.out.println("加法运算后="+s2);
- FenShu result3=fs1.jian(fs2);
- String s3=result3.getString();
- System.out.println("减法运算后="+s3);
-
- } catch (ArithmeticException e) {
- System.out.println("分数分母为零不能运算");
- System.out.println(e.getMessage());
-
- <FONT color=red> //这儿修改一下,就两个都打印出来了
- try {
- FenShu fs2=new FenShu(5,0);
- } catch (Exception e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- </FONT> e.printStackTrace();
- }
- }
- }
- //声明一个分数类
- class FenShu {
-
- //定义分子、分母两个int型变量
- private int fz;
- private int fm;
- //构造方法
- public FenShu() {}
-
- //方法重载
- public FenShu(int fz, int fm) {
- this.fz = fz;
- this.fm = fm;
- yueFen(fz,fm);
- }
-
- //对分子、分母进行约分
- public void yueFen(int f1, int f2){
- int x = f1;
- int y = f2;
- if(x < y){
- int t;
- t = x;
- x = y;
- y = t;
- }
- int n = x % y;
- while(n!=0){
- x = y;
- y = n;
- n = x % y;
- }
- this.fz /= y;
- this.fm /= y;
- }
-
- //对分数进行加、减、乘、除四则运算
- public FenShu jia(FenShu fs) {
- int zi=this.fz*fs.fm+fs.fz*this.fm;
- int mu=this.fm*fs.fm;
- return new FenShu(zi,mu);
- }
- public FenShu jian(FenShu fs) {
- int zi=this.fz*fs.fm-fs.fz*this.fm;
- int mu=this.fm*fs.fm;
- return new FenShu(zi,mu);
- }
- public FenShu cheng(FenShu fs) {
- int zi = this.fz * fs.fz;
- int mu = this.fm * fs.fm;
- return new FenShu(zi, mu);
- }
- public FenShu chu(FenShu fs) {
- int zi =this.fz*fs.fm;
- int mu =this.fm*fs.fz;
- return new FenShu(zi,mu);
- }
- public double doubleValue() {
- return fz / fm;
- }
- public String getString() {
- return fz + "/" + fm;
- }
- }
复制代码 |