版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/suguoliang/article/details/79931117
抽象类-编程实现运算类
题目描述
编程实现运算类(1)定义抽象类Operation,有double型数据成员numberA、numberB,有抽象方法getResult()(2)定义Operation的4个子类,分别实现加、减、乘、除四则运算(3)定义类OperationFactory:有静态方法Operation createOperate(String operate); 根据形参operate的值创建相应加、减、乘、除类的对象,赋给抽象类引用后返回(4)定义测试类及主方法:用户从键盘输入运算数及运算符,根据运算符调用OperationFactory类的静态方法,创建相应实例,设置运算数,输出运行结果
输入描述
样例输入(每次运行输入一个式子:数据与运算符之间一个空格间隔)
输出描述
一行输出结果:冒号、感叹号均为中文标点
输入样例
56 + 1234 / 1745 / 0
输出样例
结果是:68.0结果是:2.0
除数不能为0!
import java.util.Scanner;
abstract class Operation
{
double numberA,numberB;
abstract double getResult() throws Exception;
}
class AddOperation extends Operation
{
double getResult() throws Exception
{
return numberA+numberB;
}
}
class subOperation extends Operation
{
double getResult() throws Exception
{
return numberA-numberB;
}
}
class chengOperation extends Operation
{
double getResult() throws Exception
{
return numberA*numberB;
}
}
class DivideOperation extends Operation{
double getResult() throws Exception
{
if(numberB==0)
throw new Exception("除数不能为0!");
return numberA/numberB;
}
}
class OperationFactory{
public static Operation createOperate(String operate)
{
if(operate.equals("+"))
return new AddOperation();
if(operate.equals("-"))
return new subOperation();
if(operate.equals("*"))
return new chengOperation();
else //if(operate.equals("/"))
return new DivideOperation();
}
}
public class Main{
public static void main(String[] args)
{
double x,y,z;
String op;
Scanner in=new Scanner(System.in);
while(in.hasNext())
{
x=in.nextDouble();
op=in.next();
y=in.nextDouble();
Operation oper=OperationFactory.createOperate(op);
oper.numberA=x;
oper.numberB=y;
try{
z=oper.getResult();
System.out.print("结果是:"+z);
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}