Java不同计算器的基本函数问题?

Java不同计算器的基本函数问题?,java,Java,下面的代码是计算器实际代码的一部分。它所做的是,用户按下计算器上的一个数字,然后当他按下“+”时,文本字段上的数字被存储,然后他按下下一个数字,当他按下“=”时,它被存储。然后在“=”中如果条件是执行加法功能。现在我希望加法和减法同时运行,即在执行加法后用户希望执行减法,那么我将如何执行 if(a.getActionCommand().equals("+")) { q=tf.getText(); x=Integer.parseInt(q); } if(a.getActionComm

下面的代码是计算器实际代码的一部分。它所做的是,用户按下计算器上的一个数字,然后当他按下“+”时,文本字段上的数字被存储,然后他按下下一个数字,当他按下“=”时,它被存储。然后在“=”中如果条件是执行加法功能。现在我希望加法和减法同时运行,即在执行加法后用户希望执行减法,那么我将如何执行

if(a.getActionCommand().equals("+"))
{
   q=tf.getText();
   x=Integer.parseInt(q);
}

if(a.getActionCommand().equals("-"))
{
   b=tf.getText();
   t=Integer.parseInt(b);
}
if(a.getActionCommand().equals("="))
{
   p=tf.getText();
   y=Integer.parseInt(p);
   z=x+y;
   //z=t-y;
   w=Integer.toString(z);
   tf.setText(w);
}

如何:接受负数作为输入,然后添加?还是我没抓住重点

如果没有,那么使用RPN就可以了,根本不需要“=”。输入两个数字,然后“+”或“-”将从堆栈中取出两个操作数,应用运算符,并将结果推回堆栈,显示结果

第三种方法:使用以下代码代替“-”代码:


不确定我是否考虑了最后一个建议的所有内容,但这只是一个开始。

计算器通常在处理像
+
-
这样的操作时执行
=
操作。尝试一下,现在打开计算机上的calc应用程序,然后尝试
3+5-1
。按
-
时,显示屏将显示
8
。您可以对自己的操作执行相同的操作,并按自己的意愿处理一行中的任意多个
+
-
操作。您发布的代码需要进行一些重构,您可以做的一件事是系统化用于
=
操作的流程。然后,您可以在每个
+
-
块的开头调用
performEquals

jcomeau\u ictx建议的基于堆栈的算法是解决问题的非常可行的方法

创建两个堆栈:一个保存运算符(+、-、*、/),另一个保存操作数(数字集0-9)

支持用户按:3+4-5

Steps:

1.) Push '3' into the operand stack
2.) Push '+' into the operator stack
3.) Push '4' into the operand stack.

Since there are at least 2 operands, calculate 3 + 4 (which is 7).

4.) Pop 3 and 4.  Add these two and pop them to the operand stack
5.) Pop + from the operator stack and push -.
6.) Push 5 onto the stack.  Subtract these two and place result in operand stack.
通用算法:

Push operand (or operator) into the stack
if (operands > 2 && operator > 0)
     pop both operands and one operator;
     calculate result;
     place result in operand stack;
     reset operator stack;

我假设您有4个操作(+、-、×、÷),并且您正在实现一个基本的桌面计算器,不实现操作顺序。在这种情况下,
x=-(Integer.parseInt(b))
将不起作用,因为它只能处理减法运算,而不能处理乘法和除法运算,而且这些基于堆栈的解决方案是多余的

您使用的是3个变量:
firstNumber
operation
secondNumber
<代码>操作开始时为空(或使用指示“空”的某个值)。当用户点击=,您需要做的是从显示器中取出数字并将其放入
secondNumber
。然后查看所有3个变量,并执行
操作中指示的操作


当用户点击+、-、×、或÷时,首先执行=操作(将用户的输入放入
secondNumber
并执行
operation
变量指示的操作)。将结果放入
firstNumber
(如果愿意,可在屏幕上显示)。然后将用户点击(+、-、×、或÷)的操作存储在
操作
变量中,这样下次用户点击+、-、×、÷或=,您就可以执行该操作了。

基本上我有一段时间想用java制作一个计算器,这样我就可以在考试前练习gui课程了。
Push operand (or operator) into the stack
if (operands > 2 && operator > 0)
     pop both operands and one operator;
     calculate result;
     place result in operand stack;
     reset operator stack;