有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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);
}

共 (4) 个答案

  1. # 1 楼答案

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

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

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

  2. # 2 楼答案

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

  3. # 3 楼答案

    jcomeau_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. # 4 楼答案

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

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

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

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

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