android studio四则运算
时间: 2023-04-28 08:05:39 浏览: 131
四则运算
4星 · 用户满意度95%
Android Studio可以用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) {
double result = 0;
try {
result = eval(expression);
} catch (Exception e) {
System.out.println("表达式不合法!");
}
return result;
}
public static double eval(String expression) {
return new Object() {
int pos = -1, ch;
void nextChar() {
ch = (++pos < expression.length()) ? expression.charAt(pos) : -1;
}
boolean eat(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
double parse() {
nextChar();
double x = parseExpression();
if (pos < expression.length()) throw new RuntimeException("表达式不合法!");
return x;
}
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm();
else if (eat('-')) x -= parseTerm();
else return x;
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor();
else if (eat('/')) x /= parseFactor();
else return x;
}
}
double parseFactor() {
if (eat('+')) return parseFactor();
if (eat('-')) return -parseFactor();
double x;
int startPos = this.pos;
if (eat('(')) {
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') {
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(expression.substring(startPos, this.pos));
} else if (ch >= 'a' && ch <= 'z') {
while (ch >= 'a' && ch <= 'z') nextChar();
String func = expression.substring(startPos, this.pos);
x = parseFactor();
if (func.equals("sqrt")) x = Math.sqrt(x);
else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
else throw new RuntimeException("未知的函数:" + func);
} else {
throw new RuntimeException("表达式不合法!");
}
if (eat('^')) x = Math.pow(x, parseFactor());
return x;
}
}.parse();
}
}
```
这个程序可以接受用户输入一个表达式,然后计算出结果。例如,如果用户输入“2+3*4”,程序将输出“14.0”。
阅读全文