在Android中使用单选按钮进行数学运算可以通过以下步骤实现:
以下是一个示例代码:
// MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;
private EditText operand1EditText;
private EditText operand2EditText;
private Button calculateButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = findViewById(R.id.radioGroup);
operand1EditText = findViewById(R.id.operand1EditText);
operand2EditText = findViewById(R.id.operand2EditText);
calculateButton = findViewById(R.id.calculateButton);
calculateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedId = radioGroup.getCheckedRadioButtonId();
double operand1 = Double.parseDouble(operand1EditText.getText().toString());
double operand2 = Double.parseDouble(operand2EditText.getText().toString());
double result = 0;
switch (selectedId) {
case R.id.addRadioButton:
result = operand1 + operand2;
break;
case R.id.subtractRadioButton:
result = operand1 - operand2;
break;
case R.id.multiplyRadioButton:
result = operand1 * operand2;
break;
case R.id.divideRadioButton:
if (operand2 != 0) {
result = operand1 / operand2;
} else {
Toast.makeText(MainActivity.this, "Cannot divide by zero", Toast.LENGTH_SHORT).show();
return;
}
break;
}
Toast.makeText(MainActivity.this, "Result: " + result, Toast.LENGTH_SHORT).show();
}
});
}
}
请注意,这只是一个简单的示例,仅涵盖了基本的数学运算。在实际应用中,您可能需要添加更多的错误处理和验证逻辑。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云