用Android stdio写一个复杂计算机
时间: 2024-03-17 14:42:34 浏览: 54
好的,下面是一个简单的 Android 应用程序,可以执行复杂计算。它提供了一个基本的用户界面,允许用户输入表达式并计算结果。请注意,这个应用程序仅用于演示目的,还需要进行更多的测试和优化。
1. 创建一个新的 Android 项目并命名为 "Calculator"。
2. 打开 activity_main.xml 文件,并添加一个 TextView 元素用于显示计算结果,以及一个 EditText 元素用于接受用户输入的表达式。例如:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/result_textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textStyle="bold" />
<EditText
android:id="@+id/expression_edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter expression"
android:inputType="text"
android:textSize="18sp" />
<Button
android:id="@+id/calculate_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Calculate" />
</LinearLayout>
```
3. 打开 MainActivity.java 文件,并添加以下代码:
```java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MainActivity extends AppCompatActivity {
private TextView resultTextView;
private EditText expressionEditText;
private Button calculateButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultTextView = findViewById(R.id.result_textview);
expressionEditText = findViewById(R.id.expression_edittext);
calculateButton = findViewById(R.id.calculate_button);
calculateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String expression = expressionEditText.getText().toString();
new CalculateTask().execute(expression);
}
});
}
private class CalculateTask extends AsyncTask<String, Void, BigDecimal> {
@Override
protected BigDecimal doInBackground(String... expressions) {
String expression = expressions[0];
try {
BigDecimal result = evaluateExpression(expression);
return result;
} catch (Exception e) {
Log.e("Calculator", "Error evaluating expression: " + expression, e);
return null;
}
}
@Override
protected void onPostExecute(BigDecimal result) {
if (result == null) {
resultTextView.setText("Error evaluating expression");
} else {
resultTextView.setText(result.toString());
}
}
private BigDecimal evaluateExpression(String expression) {
List<String> tokens = tokenizeExpression(expression);
List<String> postfixTokens = convertToPostfix(tokens);
BigDecimal result = evaluatePostfix(postfixTokens);
return result;
}
private List<String> tokenizeExpression(String expression) {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c) || c == '.') {
sb.append(c);
} else if (isOperator(c)) {
if (sb.length() > 0) {
tokens.add(sb.toString());
sb.setLength(0);
}
tokens.add("" + c);
} else if (Character.isWhitespace(c)) {
if (sb.length() > 0) {
tokens.add(sb.toString());
sb.setLength(0);
}
} else {
throw new IllegalArgumentException("Invalid character in expression: " + expression);
}
}
if (sb.length() > 0) {
tokens.add(sb.toString());
}
return tokens;
}
private List<String> convertToPostfix(List<String> tokens) {
Stack<String> operatorStack = new Stack<>();
List<String> postfixTokens = new ArrayList<>();
for (String token : tokens) {
if (isOperator(token)) {
while (!operatorStack.isEmpty() && precedence(operatorStack.peek()) >= precedence(token)) {
postfixTokens.add(operatorStack.pop());
}
operatorStack.push(token);
} else if (token.equals("(")) {
operatorStack.push(token);
} else if (token.equals(")")) {
while (!operatorStack.isEmpty() && !operatorStack.peek().equals("(")) {
postfixTokens.add(operatorStack.pop());
}
if (!operatorStack.isEmpty() && operatorStack.peek().equals("(")) {
operatorStack.pop();
} else {
throw new IllegalArgumentException("Mismatched parentheses in expression");
}
} else {
postfixTokens.add(token);
}
}
while (!operatorStack.isEmpty()) {
String operator = operatorStack.pop();
if (operator.equals("(")) {
throw new IllegalArgumentException("Mismatched parentheses in expression");
}
postfixTokens.add(operator);
}
return postfixTokens;
}
private BigDecimal evaluatePostfix(List<String> tokens) {
Stack<BigDecimal> operandStack = new Stack<>();
for (String token : tokens) {
if (isOperator(token)) {
BigDecimal operand2 = operandStack.pop();
BigDecimal operand1 = operandStack.pop();
BigDecimal result = evaluateOperator(token, operand1, operand2);
operandStack.push(result);
} else {
BigDecimal operand = new BigDecimal(token);
operandStack.push(operand);
}
}
if (operandStack.size() != 1) {
throw new IllegalArgumentException("Invalid postfix expression");
}
return operandStack.pop();
}
private boolean isOperator(String token) {
return "+-*/".indexOf(token) != -1;
}
private int precedence(String operator) {
if (operator.equals("+") || operator.equals("-")) {
return 1;
} else if (operator.equals("*") || operator.equals("/")) {
return 2;
} else {
return 0;
}
}
private BigDecimal evaluateOperator(String operator, BigDecimal operand1, BigDecimal operand2) {
MathContext mc = new MathContext(10);
if (operator.equals("+")) {
return operand1.add(operand2, mc);
} else if (operator.equals("-")) {
return operand1.subtract(operand2, mc);
} else if (operator.equals("*")) {
return operand1.multiply(operand2, mc);
} else if (operator.equals("/")) {
return operand1.divide(operand2, mc);
} else {
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
}
}
```
这个代码实现了一个 AsyncTask 内部类,用于在后台线程上计算表达式的值。它实现了以下步骤:
- tokenizeExpression():将输入字符串分解为单独的数字和操作符。
- convertToPostfix():将中缀表达式转换为后缀表达式,以方便计算。
- evaluatePostfix():计算后缀表达式的值,并返回结果。
请注意,这个实现仅支持四个基本操作符(+、-、*、/),如果需要支持更多的操作符,需要进行更多的修改。
4. 运行应用程序,输入表达式并点击计算按钮,应该可以看到计算结果。
阅读全文