Java implements simple four arithmetic operations (2+3×5+4×6)
Realization: The arithmetic number is written in the main function without keyboard typing, and the result is obtained after running.
Mainly pay attention to the following points:
- Do not use return in the constructor, and use return in the constructor to return an int value, which does not match the Mul type of the created object.
- A class can have multiple construction methods , and two construction methods with the same name are used in the Add class.
Sequence diagram :
The specific code is as follows:
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();
}
}