📅  最后修改于: 2023-12-03 15:29:56.010000             🧑  作者: Mango
calc
是一款使用Java编写的命令行计算器程序,具有基本的算术运算功能。它可以读取用户输入的数学表达式并返回计算结果。
javac
命令编译源代码:javac Calc.java
calc
命令:java Calc
当您运行calc
程序时,您将看到一个>
符号,这意味着它已准备好接收您的输入。
您可以输入任何合法的数学表达式,包括括号、浮点数和负数。输入完成后,按Enter
键,程序将输出计算结果。
以下是一些示例输入和输出:
> 2+2
4.0
> (1+2)*3
9.0
> 10/3
3.3333333333333335
> -5
-5.0
> 3.1415926535897932384626433832795028841971*2
6.283185307179586
以下是Calc.java
的源代码:
import java.util.*;
import java.math.*;
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("> ");
String expr = sc.nextLine();
if(expr.equals("exit")) {
break;
}
try {
double result = eval(expr);
System.out.println(result);
} catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
sc.close();
}
public static double eval(String expr) throws Exception {
Stack<Double> nums = new Stack<>();
Stack<Character> ops = new Stack<>();
for(int i = 0; i < expr.length(); i++) {
char ch = expr.charAt(i);
if(ch == ' ') {
continue;
}
else if(ch == '(') {
ops.push(ch);
}
else if(isNumber(ch)) {
int j = i;
while(j < expr.length() && (isNumber(expr.charAt(j)) || expr.charAt(j) == '.')) {
j++;
}
double num = Double.parseDouble(expr.substring(i, j));
nums.push(num);
i = j - 1;
}
else if(ch == '+' || ch == '-' || ch == '*' || ch == '/') {
while(!ops.isEmpty() && !higherPrecedence(ops.peek(), ch)) {
double num2 = nums.pop();
double num1 = nums.pop();
char op = ops.pop();
nums.push(applyOp(num1, num2, op));
}
ops.push(ch);
}
else if(ch == ')') {
while(ops.peek() != '(') {
double num2 = nums.pop();
double num1 = nums.pop();
char op = ops.pop();
nums.push(applyOp(num1, num2, op));
}
ops.pop();
}
else {
throw new Exception("Invalid character: " + ch);
}
}
while(!ops.isEmpty()) {
double num2 = nums.pop();
double num1 = nums.pop();
char op = ops.pop();
nums.push(applyOp(num1, num2, op));
}
return nums.pop();
}
public static boolean isNumber(char ch) {
return (ch >= '0' && ch <= '9');
}
public static boolean higherPrecedence(char op1, char op2) {
if(op1 == '(' || op1 == ')') {
return false;
}
if((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return true;
}
return false;
}
public static double applyOp(double num1, double num2, char op) throws Exception {
switch(op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
if(num2 == 0) {
throw new Exception("Cannot divide by zero.");
}
return num1 / num2;
default:
throw new Exception("Invalid operator: " + op);
}
}
}