|
public class Calcuation
{
public double NumberA;
public double NumberB;
public double getNumberA()
{
return NumberA;
}
public void setNumberA(double numberA)
{
NumberA = numberA;
}
public double getNumberB()
{
return NumberB;
}
public void setNumberB(double numberB)
{
NumberB = numberB;
}
public double result()
{
return 0;
}
}
class Add extends Calcuation
{
public double result()
{
return getNumberA() + getNumberB();
}
}
class Subtract extends Calcuation
{
public double result()
{
return getNumberA() - getNumberB();
}
}
class Multiply extends Calcuation
{
public double result()
{
return getNumberA() * getNumberB();
}
}
class Divide extends Calcuation
{
public double result()
{
if (getNumberB() == 0)
{
try
{
throw new Exception("Divisor can't for 0");
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return getNumberA() / getNumberB();
}
}
public class FactoryModer
{
static char a;
public static Calcuation createObject(String operator)
{
Calcuation calcuation = null;
a = operator.charAt(0);
switch (a)
{
case '+':
calcuation = new Add();
break;
case '-':
calcuation = new Subtract();
break;
case '*':
calcuation = new Multiply();
break;
case '/':
calcuation = new Divide();
break;
}
return calcuation;
}
}
import java.util.Scanner;
public class Operator
{
static double resultNumber = 0;
static double num1;
static double num2;
static String operatorString;
public static void main(String[] args)
{
paint();
}
public static void paint()
{
Scanner scanner = new Scanner(System.in);
System.out.println("please input oen number:");
num1 = scanner.nextDouble();
System.out.println("please input a operator:");
operatorString = scanner.next();
System.out.println("please input two number:");
num2 = scanner.nextDouble();
Calcuation calcuation = null;
calcuation.NumberA = num1;
calcuation.NumberB = num2;
calcuation = FactoryModer.cr2eateObject(operatorString);
resultNumber = calcuation.result();
System.out.println(resultNumber);
}
}
欢迎来到Java学习者论坛,zhuan载请注明地址:http://www.javaxxz.com. |
|