在看《大話設計模式》這本書,在開篇的第一部分介紹面向對象時候,介紹了一位童鞋面試時面試官讓他使用面嚮對象語言實現一個簡單的計算器,然而這位同學卻沒能很好地理解考官的意思,導致面試失敗。那麼如何使用Java語言以面向對象的思想去實現這樣的一個簡單的計算器呢?
本文給出兩種實現的方式。
實現1:
import java.util.Scanner;
/*
* 《大話設計模式》中的計算器實現代碼
* */
public class Operation {
public static double GetResult(double numA, double numB, String opr) {
double result = 0d;
switch (opr) {
case "+":
result = numA + numB;
break;
case "-":
result = numA - numB;
break;
case "*":
result = numA * numB;
break;
case "/":
result = numA / numB;
break;
}
return result;
}
public static void main(String[] args) {
System.out.println("請輸入數字A:");
Scanner scan = new Scanner(System.in);
String strNumA = scan.nextLine();
System.out.println("請輸入運算符號(+、-、*、/):");
String strOpr = scan.nextLine();
System.out.println("請輸入數字B");
String strNumB = scan.nextLine();
String strResult = "";
double Result = GetResult(Double.parseDouble(strNumA), Double.parseDouble(strNumB), strOpr);
strResult = String.valueOf(Result);
System.out.println(strResult);
}
}
實現2:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
System.out.println("-----------------------------------");
System.out.println("請輸入一個算術表達式,如:45*23");
Scanner in = new Scanner(System.in);
String str = in.nextLine();
StringBuffer buffer = new StringBuffer();
StringBuffer buffer1 = new StringBuffer();
char t = ' ';
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '+' || str.charAt(i) == '-'
|| str.charAt(i) == '*' || str.charAt(i) == '/') {
t = str.charAt(i);
for (int j = i + 1; j < str.length(); j++) {
buffer1.append(str.charAt(j));
}
break;
} else {
buffer.append(str.charAt(i));
}
}
String c = buffer.toString();
String d = buffer1.toString();
double a = Double.parseDouble(c);
double b = Double.parseDouble(d);
double sum = 0;
if (t == '+') {
sum = a + b;
}
if (t == '-') {
sum = a - b;
}
if (t == '*') {
sum = a * b;
}
if (t == '/') {
sum = a / b;
}
System.out.println("程序運算...");
System.out.println(c+t+d+"="+sum);
System.out.print("-----------------------------------");
}
}