[英]AWT Choice in a calculator
I basically don't know how to forward the value I get from a Choice and use it in a equation later on.我基本上不知道如何转发我从 Choice 获得的价值,并在以后的方程式中使用它。
I'm building a calculator and I need to have a Choice control with operations and a button that calculates with the operation selected in the Choice.我正在构建一个计算器,我需要一个带有操作的 Choice 控件和一个使用 Choice 中选择的操作进行计算的按钮。
b1 = Calculate button
This is the equation I use这是我使用的等式
Double n1 = Double.parseDouble(t1.getText());
Double n2 = Double.parseDouble(t2.getText());
if (e.getSource() == b1) {
t3.setText(String.valueOf(n1 [here should be the operator selected from the Choice] n2)); }
The idea is when clicked on the button Calculate n1 and n2 should perform operation selected in Choice control.这个想法是当点击按钮计算 n1 和 n2 时应该执行在 Choice 控件中选择的操作。
[ enter image description here ]( https://i.stack.imgur.com/9Dqwa.png ) [在此处输入图片描述]( https://i.stack.imgur.com/9Dqwa.png )
Check the API documentation about Choice.查看有关 Choice 的API 文档。 That class offers the methods getSelectedItem() and getSelectedIndex() that you can use in your event listener. class 提供了您可以在事件侦听器中使用的方法getSelectedItem()和getSelectedIndex() 。
Here is an example:这是一个例子:
if (e.getSource() == b1) {
switch(choice.getSelectedIndex()) {
case 0:
t3.setText(String.valueOf(n1 + n2));
break;
case 1:
t3.setText(String.valueOf(n1 - n2));
break;
case 2:
t3.setText(String.valueOf(n1 * n2));
break;
case 3:
t3.setText(String.valueOf(n1 / n2));
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.