Java实现简单四则运算(2+3×5+4×6)

Java实现简单四则运算(2+3×5+4×6)

实现:运算数字实现不用键盘敲入,写在main函数中,运行即获得结果。

主要注意以下几点:

  1. 不在构造方法中用return ,构造方法中用return的话返回int型数值,与创建对象的Mul类型不符。
  2. 一个类可以有多个构造方法 ,Add类里就用了两个同名构造方法。

顺序图
在这里插入图片描述

具体代码如下:

public class M {
    
    
public static void main(String[] args) {
    
    
	Mul o1=new Mul(3,5);
	Mul o2=new Mul(6,4);
	Add o3=new Add(2,o1);
	Add o4=new Add(o3,o2);
	System.out.println(o4.getValue());
	}
}
class Mul{
    
    
	int a;
	int b;
	public Mul(int a, int b) {
    
    
		// TODO Auto-generated constructor stub
		this.a=a;
		this.b=b;
		getValue();
		}

	public int getValue() {
    
    
		// TODO Auto-generated method stub
		return a*b;
	}
}
class Add{
    
    
	Add i; Mul j;
	int a; Mul b;
	public Add(int a, Mul b) {
    
    
		// TODO Auto-generated constructor stub
		this.a=a;
		this.b=b;
		getValue1();
	}
	
	int getValue1() {
    
    
		// TODO Auto-generated method stub
		return a+b.getValue();
	}
	
	public Add(Add i, Mul j) {
    
    
		// TODO Auto-generated constructor stub
		this.i=i;
		this.j=j;
		getValue();
	}
	int getValue() {
    
    
		// TODO Auto-generated method stub
		return i.getValue1()+j.getValue();
	}
	
}

猜你喜欢

转载自blog.csdn.net/weixin_46020391/article/details/109287950