android studio设计计算器复数或非运算
时间: 2023-09-12 13:11:00 浏览: 172
android studio实现计算器
5星 · 资源好评率100%
以下是一个简单的Android Studio计算器应用程序,可以进行复数或非运算:
1. 创建一个新的Android Studio项目,并在布局文件中添加一个TextView和多个Button。
2. 在MainActivity.java中添加以下代码:
```
public class MainActivity extends AppCompatActivity {
TextView resultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = findViewById(R.id.resultText);
}
public void onButtonClick(View view) {
Button button = (Button) view;
String buttonText = button.getText().toString();
String result = resultText.getText().toString();
switch (buttonText) {
case "C":
resultText.setText("");
break;
case "+/-":
if (result.startsWith("-")) {
resultText.setText(result.substring(1));
} else {
resultText.setText("-" + result);
}
break;
case "=":
if (result.contains("+")) {
String[] parts = result.split("\\+");
double real = Double.parseDouble(parts[0]);
double imaginary = Double.parseDouble(parts[1].replace("i", ""));
ComplexNumber complexNumber = new ComplexNumber(real, imaginary);
resultText.setText(complexNumber.toString());
} else if (result.contains("-")) {
String[] parts = result.split("-");
double real = Double.parseDouble(parts[0]);
double imaginary = Double.parseDouble(parts[1].replace("i", ""));
ComplexNumber complexNumber = new ComplexNumber(real, -imaginary);
resultText.setText(complexNumber.toString());
} else {
resultText.setText(result);
}
break;
default:
resultText.setText(result + buttonText);
break;
}
}
}
```
3. 添加一个名为ComplexNumber的新类,用于执行复数运算:
```
public class ComplexNumber {
private double real;
private double imaginary;
public ComplexNumber(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public double getReal() {
return real;
}
public void setReal(double real) {
this.real = real;
}
public double getImaginary() {
return imaginary;
}
public void setImaginary(double imaginary) {
this.imaginary = imaginary;
}
@Override
public String toString() {
if (imaginary == 0) {
return String.format("%.2f", real);
} else if (real == 0) {
return String.format("%.2fi", imaginary);
} else {
return String.format("%.2f + %.2fi", real, imaginary);
}
}
}
```
4. 运行应用程序并测试复数或非运算。
阅读全文