不知道你们有没有遇到这种情况,面试题中只有一道题,(例:用面向对象的思想用控制台去写一个计算器小程序,其中包含'+' '-' '*' '/' 功能,输入两个数可算出结果)
常常很多人都会以为很简单,都会这么答:
import java.util.*;
class Counter{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("----请输入第一个数----");
double number_1 = in.nextDouble();
System.out.println("----请输入一个算术运算符(例如:+/-/*)");
String operate = in.next();
System.out.println("----请输入第二个数----");
double number_2 = in.nextDouble();
double res = 0;
switch (operate){
case "+":
res = number_1+number_2;
break;
case "-":
res = number_1-number_2;
break;
case "*":
res = number_1*number_2;
break;
case "/":
res = number_1/number_2;
break;
}
System.out.println( number_1 + operate + number_2 +"="+ res);
}
}
但是很多人都忽略一个关键词就是用“面向对象”的思想,我觉得应该这么写,以显示出面向对象的 封装 继承 多态的 核心理念
import java.util.*;
//定义一个抽象类
abstract class Counter {
abstract double getResult();
}
//定义一个加法类
class Add extends Counter{
private double number_1 = 0;
private double number_2 = 0;
//构造函数
Add(double p_Number1,double p_Number2)
{
this.number_1 = p_Number1;
this.number_2 = p_Number2;
}
double getResult()
{
return this.number_1+this.number_2;
}
}
//定义一个减法类
class Sub extends Counter{
private double number_1 = 0;
private double number_2 = 0;
Sub(double p_Number1,double p_Number2)
{
this.number_1 = p_Number1;
this.number_2 = p_Number2;
}
double getResult()
{
return this.number_1-this.number_2;
}
}
//定义一个乘法类
class Mul extends Counter{
private double number_1 = 0;
private double number_2 = 0;
Mul(double p_Number1,double p_Number2)
{
this.number_1 = p_Number1;
this.number_2 = p_Number2;
}
double getResult()
{
return this.number_1 * this.number_2;
}
}
//定义一个除法类
class Div extends Counter{
private double number_1 = 0;
private double number_2 = 0;
Div(double p_Number1,double p_Number2)
{
this.number_1 = p_Number1;
this.number_2 = p_Number2;
}
double getResult()
{
return this.number_1/this.number_2;
}
}
//定义一个运算类
class Operate{
static double operate(double p_Number1,double p_Number2,String p_Op)
{
Counter cou = null;
switch (p_Op){
case "+":
cou = new Add(p_Number1,p_Number2);
break;
case "-":
cou = new Sub(p_Number1,p_Number2);
break;
case "*":
cou = new Mul(p_Number1,p_Number2);
break;
case "/":
cou = new Div(p_Number1,p_Number2);
break;
}
return cou.getResult();
}
}
class Demo{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("----请输入一个数-----");
double number_1 = in.nextDouble();
System.out.println("----请输入一个运算符(如:+|-|*|/)----");
String ope = in.next();
System.out.println("----请输入第二个数-----");
double number_2 = in.nextDouble();
double res = Operate.operate(number_1,number_2,ope);
System.out.println(number_1 + ope + number_2 +" = " + res);
}
} |
|