//定义一个运算符(+ - * /)接口,定义不同的运算类分别表示上线这个接口并进行相应的运算
//File:OperationTest.java
import java.util.Scanner;
interface Operation{
double getResult(double numA,double numB);
}
class Plus implements Operation{
public double getResult(double numA,double numB){
return numA+numB;
}
}
class Minus implements Operation{
public double getResult(double numA,double numB){
return numA-numB;
}
}
class Mult implements Operation{
public double getResult(double numA,double numB){
return numA*numB;
}
}
class Div implements Operation{
public double getResult(double numA,double numB){
if(numB==0){
System.out.println("除数不能为0!");
return 0;
}
return numA/numB;
}
}
public class OperationTest{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("请输入两个数字:");
double dataA=input.nextDouble();
double dataB=input.nextDouble();
System.out.println("请输入运算符(+ - * /):");
char op=input.next().charAt(0);
Operation operation=null;
switch(op){
case '+':
operation=new Plus();break;
case '-':
operation=new Minus();break;
case '*':
operation=new Mult();break;
case '/':
operation=new Div();break;
default:
System.out.println("输入错误!");
}
System.out.println(operation.getResult(dataA,dataB));
}
}
//File:OperationTest.java
import java.util.Scanner;
interface Operation{
double getResult(double numA,double numB);
}
class Plus implements Operation{
public double getResult(double numA,double numB){
return numA+numB;
}
}
class Minus implements Operation{
public double getResult(double numA,double numB){
return numA-numB;
}
}
class Mult implements Operation{
public double getResult(double numA,double numB){
return numA*numB;
}
}
class Div implements Operation{
public double getResult(double numA,double numB){
if(numB==0){
System.out.println("除数不能为0!");
return 0;
}
return numA/numB;
}
}
public class OperationTest{
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("请输入两个数字:");
double dataA=input.nextDouble();
double dataB=input.nextDouble();
System.out.println("请输入运算符(+ - * /):");
char op=input.next().charAt(0);
Operation operation=null;
switch(op){
case '+':
operation=new Plus();break;
case '-':
operation=new Minus();break;
case '*':
operation=new Mult();break;
case '/':
operation=new Div();break;
default:
System.out.println("输入错误!");
}
System.out.println(operation.getResult(dataA,dataB));
}
}