刚好用设计模式(简单工厂模式)编写了一个计算器。
专注于为中小企业提供成都网站建设、网站设计服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业怒江州免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。
package com.medavis.simplefactory.ui;
import java.util.Scanner;
import com.medavis.simplefactory.operate.OperatorFactory;
public class CaculatorUI {
private static Scanner sc;
public static void main(String[] args) {
try {
System.out.println("Please input a number:");
sc = new Scanner(System.in);
long first = sc.nextLong();
System.out.println("Please input a operational character (+-*/):");
sc = new Scanner(System.in);
String operator = sc.nextLine();
System.out.println("Please input a number:");
sc = new Scanner(System.in);
long second = sc.nextLong();
OperatorFactory opf=new OperatorFactory();
System.out.println(first + operator + second + "=" + opf.getOperator(operator).getResult(first, second));
} catch(Exception e) {
System.out.println("Your input is wrong!");
}
}
}
package com.medavis.simplefactory.operate;
public class OperatorAdd extends Operator{
@Override
public long getResult(long first, long second) {
return first+second;
}
}
package com.medavis.simplefactory.operate;
public class OperatorDiv extends Operator{
@Override
public long getResult(long first, long second) {
return first/second;
}
}
package com.medavis.simplefactory.operate;
public class OperatorFactory {
public Operator getOperator(String operator) throws Exception{
switch(operator){
case "+":
return new OperatorAdd();
case "-":
return new OperatorSub();
case "*":
return new OperatorMul();
case "/":
return new OperatorDiv();
default:
throw new Exception();
}
}
}
package com.medavis.simplefactory.operate;
public class OperatorMul extends Operator {
@Override
public long getResult(long first, long second) {
return first*second;
}
}
package com.medavis.simplefactory.operate;
public class OperatorSub extends Operator{
@Override
public long getResult(long first, long second) {
return first-second;
}
}
主要涉及的知识点: 类的写法, 以及方法的调用 .建议多做练习. 如果有看不懂的地方. 可以继续追问,一起讨论.
参考代码如下
//Number类
class Number {
private int n1;//私有的整型数据成员n1
private int n2;//私有的整型数据成员n2
// 通过构造函数给n1和n2赋值
public Number(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
// 加法
public int addition() {
return n1 + n2;
}
// 减法
public int subtration() {
return n1 - n2;
}
// 乘法
public int multiplication() {
return n1 * n2;
}
// 除法 (可能除不尽,所以使用double作为返回类型)
public double division() {
return n1 * 1.0 / n2; // 通过n1*1.0 把计算结果转换成double类型.
}
}
//Exam4 类
public class Exam4{
public static void main(String[] args) {
Number number=new Number(15, 6);//创建Number类的对象
//下面的是调用方法得到返回值进行输出显示
System.out.println("加法"+number.addition());
System.out.println("减法"+number.subtration());
System.out.println("乘法"+number.multiplication());
System.out.println("除法"+number.division());
}
}
java中字符串的相等,请不要用==号,应该改成s.equals("==")
else
if(s=="退格"){
a=a/10;
}
这个方法不太好,比如我输入1,再退格,应该等于0.1吗?