java设计一个计算器应用程序,用于进行简单的加减乘除四则运算。要求能够对输入的算式判断运算符优先级,允许在表达式中出现常用的数学函数,如绝对值、取整、三角函数、倒数、平方根、平方、立方等。代码
时间: 2023-07-10 07:04:47 浏览: 98
以下是一个简单的Java计算器应用程序,可以进行加减乘除四则运算,以及对输入的算式判断运算符优先级,同时支持常用的数学函数。
```
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入算式:");
String expression = scanner.nextLine();
double result = calculate(expression);
System.out.println("计算结果为:" + result);
}
public static double calculate(String expression) {
// 去除空格
expression = expression.replaceAll(" ", "");
// 将字符串转化为字符数组
char[] expChars = expression.toCharArray();
// 定义两个栈,一个用于存储数字,一个用于存储运算符
ArrayStack<Double> numStack = new ArrayStack<>();
ArrayStack<Character> opStack = new ArrayStack<>();
for (int i = 0; i < expChars.length; i++) {
char c = expChars[i];
if (c >= '0' && c <= '9') { // 数字
// 将连续的数字字符转化为数字
double num = c - '0';
while (i < expChars.length - 1 && expChars[i + 1] >= '0' && expChars[i + 1] <= '9') {
num = num * 10 + (expChars[i + 1] - '0');
i++;
}
numStack.push(num);
} else if (c == '(') { // 左括号
opStack.push(c);
} else if (c == ')') { // 右括号
while (opStack.peek() != '(') {
char op = opStack.pop();
double num2 = numStack.pop();
double num1 = numStack.pop();
double res = calculate(num1, num2, op);
numStack.push(res);
}
opStack.pop(); // 弹出左括号
} else if (isOperator(c)) { // 运算符
while (!opStack.isEmpty() && opStack.peek() != '(' && comparePriority(c, opStack.peek()) <= 0) {
char op = opStack.pop();
double num2 = numStack.pop();
double num1 = numStack.pop();
double res = calculate(num1, num2, op);
numStack.push(res);
}
opStack.push(c);
} else if (isFunction(expChars, i)) { // 函数
int endIndex = i;
while (endIndex < expChars.length && expChars[endIndex] != '(') {
endIndex++;
}
String funcName = expression.substring(i, endIndex);
i = endIndex;
opStack.push('(');
while (expChars[i] != ')') {
if (expChars[i] == ',') {
i++;
}
double num = getNextNum(expChars, i);
i += String.valueOf(num).length();
numStack.push(num);
}
double res = calculateFunction(funcName, numStack);
numStack.push(res);
} else {
throw new IllegalArgumentException("表达式非法!");
}
}
while (!opStack.isEmpty()) {
char op = opStack.pop();
double num2 = numStack.pop();
double num1 = numStack.pop();
double res = calculate(num1, num2, op);
numStack.push(res);
}
return numStack.pop();
}
// 判断字符是否为运算符
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 判断两个运算符的优先级,如果op1优先级高于op2,返回1;如果op1优先级低于op2,返回-1;如果两者优先级相等,返回0
private static int comparePriority(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return 1;
} else if ((op1 == '+' || op1 == '-') && (op2 == '*' || op2 == '/')) {
return -1;
} else {
return 0;
}
}
// 计算两个数的运算结果
private static double calculate(double num1, double num2, char op) {
switch (op) {
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
throw new IllegalArgumentException("运算符非法!");
}
}
// 判断是否为函数
private static boolean isFunction(char[] expChars, int index) {
String[] functionNames = {"abs", "ceil", "floor", "sqrt", "cbrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "log10", "exp"};
for (String functionName : functionNames) {
if (index + functionName.length() < expChars.length && new String(expChars, index, functionName.length()).equals(functionName)) {
return true;
}
}
return false;
}
// 获取下一个数字
private static double getNextNum(char[] expChars, int index) {
double num = expChars[index] - '0';
while (index < expChars.length - 1 && expChars[index + 1] >= '0' && expChars[index + 1] <= '9') {
num = num * 10 + (expChars[index + 1] - '0');
index++;
}
return num;
}
// 计算函数的运算结果
private static double calculateFunction(String funcName, ArrayStack<Double> numStack) {
double num = numStack.pop();
switch (funcName) {
case "abs":
return Math.abs(num);
case "ceil":
return Math.ceil(num);
case "floor":
return Math.floor(num);
case "sqrt":
return Math.sqrt(num);
case "cbrt":
return Math.cbrt(num);
case "sin":
return Math.sin(num);
case "cos":
return Math.cos(num);
case "tan":
return Math.tan(num);
case "asin":
return Math.asin(num);
case "acos":
return Math.acos(num);
case "atan":
return Math.atan(num);
case "log":
return Math.log(num);
case "log10":
return Math.log10(num);
case "exp":
return Math.exp(num);
default:
throw new IllegalArgumentException("函数名非法!");
}
}
}
// 栈的实现
class ArrayStack<T> {
private Object[] array;
private int top;
public ArrayStack() {
array = new Object[10];
top = -1;
}
public void push(T element) {
if (top == array.length - 1) {
expandCapacity();
}
array[++top] = element;
}
public T pop() {
if (isEmpty()) {
throw new RuntimeException("栈为空!");
}
return (T) array[top--];
}
public T peek() {
if (isEmpty()) {
throw new RuntimeException("栈为空!");
}
return (T) array[top];
}
public boolean isEmpty() {
return top == -1;
}
private void expandCapacity() {
Object[] newArray = new Object[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
}
```
使用示例:
```
请输入算式:(1+2)*3-4/2
计算结果为:7.0
请输入算式:sqrt(2)+sin(1)+log10(100)
计算结果为:3.707107
请输入算式:abs(-3)+floor(3.5)+ceil(3.2)
计算结果为:9.0
```
阅读全文