Java简单计算器实现

最近在看大话设计模式,看到一个面试写计算器的案例。心血来潮自己也写了个。不足之处希望大家指出来

——用博客记录成长!

首先是四个算法类

package counter2;
/**
 * 加法
 * @author xhyzdZz
 *
 */
public class OperationAdd{

	public OperationAdd(double strA,double strB) {
//		double result = 0;
		System.out.println("进入add方法");
//		result = strA + strB;
		System.out.println(strA + strB);
	}
}




package counter2;
/**
 * 减法
 * @author xhyzdZz
 *
 */
public class OperationSub{

	public OperationSub(double strA,double strB) {
//		double result = 0;
//		result = strA - strB;
		System.out.println("进入sub方法...");
		System.out.println(strA - strB);
	}
}




package counter2;

/**
 * 除法
 * @author xhyzdZz
 *
 */
public class OperationDiv{

	public OperationDiv(double strA,double strB) {
//		double result = 0;
//		result = strA - strB;
		System.out.println("进入div方法...");
		System.out.println(strA / strB);
	}
}



package counter2;
/**
 * 乘法
 * @author xhyzdZz
 *
 */
public class OperationMul{

	public OperationMul(double strA,double strB) {
//		double result = 0;
//		result = strA - strB;
		System.out.println("进入mul方法...");
		System.out.println(strA * strB);
	}
}




然后是算法类

import java.util.Scanner;

/**
 * 输入方法
 *
 **/
public class input {

	public static String strOperders;//声明一个变量接收运算符

	public void inputMun() {
		try {

			Scanner sc = new Scanner(System.in);
			System.out.println("input number A:");
			double strNumberA = sc.nextInt();
                        //判断输入的运算符是否正确,错误则循环重新输入
			do {
				System.out.println("input +-*/:");
				String strOperder = sc.next();
				strOperders = strOperder;
				System.out.println("===========" + strOperders);
			} while (isOperade(strOperders));
			System.out.println("input number B:");
			double strNumberB = sc.nextInt();
			switch (strOperders) {
			case "+"://判断输入实例化对应的类,调用构造函数
				OperationAdd opa = new OperationAdd(strNumberA, strNumberB);
				break;
			case "-":
				OperationSub ops = new OperationSub(strNumberA, strNumberB);
				break;
			case "*":
				OperationMul opm = new OperationMul(strNumberA, strNumberB);
				break;
			case "/":
				OperationDiv opd = new OperationDiv(strNumberA, strNumberB);
				break;
			default:
				System.out.println("输入错误!");
				break;
			}
		} catch (NullPointerException e) {
			System.out.println(e);
		}
	}

	
	 //判断输入是否包含+-*/
	public boolean isOperade(String name) {
		String str = "+-*/";
		System.out.println(str.contains(name));
		if (str.contains(name)) {
			return false;
		}
		System.out.println("输入有误,请重新输入!");
		return true;
	}

}

最后是界面类,输入Y继续或者N结束

package counter2;

import java.util.Scanner;

public class Main {

	private static String pd = null;

	public static void main(String[] args) {
		input in = new input();
		Scanner sc = new Scanner(System.in);
		do {
			in.inputMun();
			System.out.println("Y and N:");
			pd = sc.next();
		} while (pd.equals("Y"));
	}

}

——用博客记录成长!

你可能感兴趣的:(java)