Java計算器是一種基于Java語言的計算器應用程序,可以實現基本的四則運算和復雜的科學計算。下面介紹Java計算器的流程圖和代碼。
流程圖如下:
+----------------+ | 輸入表達式 | +----------------+ | | v +----------------+ | 解析表達式 | +----------------+ | | v +----------------+ | 計算表達式 | +----------------+ | | v +----------------+ | 輸出結果 | +----------------+
代碼如下:
import java.util.*; public class Calculator { // 解析表達式 public static ListparseExpression(String expression) { List tokens = new ArrayList (); int i = 0; while (i< expression.length()) { char c = expression.charAt(i); if (c >= '0' && c<= '9' || c == '.') { // 解析數字 int j = i + 1; while (j< expression.length() && (expression.charAt(j) >= '0' && expression.charAt(j)<= '9' || expression.charAt(j) == '.')) { j++; } tokens.add(expression.substring(i, j)); i = j; } else if (c == '+' || c == '-' || c == '*' || c == '/') { // 解析運算符 tokens.add(Character.toString(c)); i++; } else { // 不支持的字符 throw new IllegalArgumentException("Unsupported character: " + c); } } return tokens; } // 計算表達式 public static double evaluateExpression(List tokens) { Stack stack = new Stack (); for (String token : tokens) { if (token.equals("+")) { double num2 = stack.pop(); double num1 = stack.pop(); stack.push(num1 + num2); } else if (token.equals("-")) { double num2 = stack.pop(); double num1 = stack.pop(); stack.push(num1 - num2); } else if (token.equals("*")) { double num2 = stack.pop(); double num1 = stack.pop(); stack.push(num1 * num2); } else if (token.equals("/")) { double num2 = stack.pop(); double num1 = stack.pop(); stack.push(num1 / num2); } else { double num = Double.parseDouble(token); stack.push(num); } } return stack.pop(); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true) { System.out.print("請輸入表達式:"); String expression = scanner.nextLine(); try { List tokens = parseExpression(expression); double result = evaluateExpression(tokens); System.out.println(expression + " = " + result); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } } }
上一篇python知乎答案
下一篇oracle 物料