java模拟计算器代码
时间: 2024-05-06 14:12:05 浏览: 61
java计算器代码
以下是Java模拟计算器的代码,实现了加减乘除和百分比的运算:
```java
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要计算的表达式:");
String expression = scanner.nextLine();
double result = calculate(expression);
System.out.println("计算结果为:" + result);
}
public static double calculate(String expression) {
double result = 0;
double num1 = 0; double num2 = 0;
char operator = ' ';
int index = 0;
int len = expression.length();
while (index < len) {
char ch = expression.charAt(index);
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
operator = ch;
index++;
} else if (ch == '%') {
if (operator == ' ') {
result = Double.parseDouble(expression.substring(0, index)) / 100;
} else {
num2 = Double.parseDouble(expression.substring(index + 1)) / 100;
result = calculate(num1, num2, operator);
}
break;
} else {
int start = index;
while (index < len && (Character.isDigit(expression.charAt(index)) || expression.charAt(index) == '.')) {
index++;
}
double num = Double.parseDouble(expression.substring(start, index));
if (operator == ' ') {
num1 = num;
} else {
num2 = num;
result = calculate(num1, num2, operator);
num1 = result;
}
}
}
return result;
}
public static double calculate(double num1, double num2, char operator) {
double result = 0;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
return result;
}
}
```
阅读全文