Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:GUI计算器一切都等于4.0_Java - Fatal编程技术网

Java:GUI计算器一切都等于4.0

Java:GUI计算器一切都等于4.0,java,Java,该程序是一个GUI计算器。出于某种原因,它的equals方法出现了问题。一切都等于4.0 我可能错过了一些非常简单的东西。我觉得我从来没有真正编写过代码来告诉它如何评估事物,尽管有人告诉我可以使用这个算法进行评估,我确实使用了这个算法(我需要使用这个算法): 还有*或/运算符 查找第一次出现的*或/在索引处 操作数将位于索引I和I+1处 对这两个操作数执行*或/运算 用结果替换这两个操作数 从操作员列表中删除您刚刚访问的操作员 结束时 返回并执行与上面完全相同的循环,但处理+和-运算符 如果您的

该程序是一个GUI计算器。出于某种原因,它的equals方法出现了问题。一切都等于4.0

我可能错过了一些非常简单的东西。我觉得我从来没有真正编写过代码来告诉它如何评估事物,尽管有人告诉我可以使用这个算法进行评估,我确实使用了这个算法(我需要使用这个算法): 还有*或/运算符 查找第一次出现的*或/在索引处 操作数将位于索引I和I+1处 对这两个操作数执行*或/运算 用结果替换这两个操作数 从操作员列表中删除您刚刚访问的操作员 结束时

返回并执行与上面完全相同的循环,但处理+和-运算符

如果您的表达式是有效的,那么下面的表达式将是真的,否则您的表达式是假的 A) 您将得到一个空的操作员列表 B) 操作数列表中将剩余一个单独的操作数。最后一个操作数是计算的结果 如果上述两个条件不成立,那么你的表达是假的

谢谢你的帮助

   import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class SimpleCalc
{
    JFrame window;  // the main window which contains everything
    Container content ;
    JButton[] digits = new JButton[12]; 
    JButton[] ops = new JButton[4];
    JTextField expression;
    JButton equals;
    JTextField result;

    public SimpleCalc()
    {
        window = new JFrame( "Simple Calc");
        content = window.getContentPane();
        content.setLayout(new GridLayout(2,1)); // 2 row, 1 col
        ButtonListener listener = new ButtonListener();

        // top panel holds expression field, equals sign and result field  
        // [4+3/2-(5/3.5)+3]  =   [3.456]

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new GridLayout(1,3)); // 1 row, 3 col

        expression = new JTextField();
        expression.setFont(new Font("verdana", Font.BOLD, 16));
        expression.setText("");

        equals = new JButton("=");
        equals.setFont(new Font("verdana", Font.BOLD, 20 ));
        equals.addActionListener( listener ); 

        result = new JTextField();
        result.setFont(new Font("verdana", Font.BOLD, 16));
        result.setText("");

        topPanel.add(expression);
        topPanel.add(equals);
        topPanel.add(result);

        // bottom panel holds the digit buttons in the left sub panel and the operators in the right sub panel
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new GridLayout(1,2)); // 1 row, 2 col

        JPanel  digitsPanel = new JPanel();
        digitsPanel.setLayout(new GridLayout(4,3)); 

        for (int i=0 ; i<10 ; i++ )
        {
            digits[i] = new JButton( ""+i );
            digitsPanel.add( digits[i] );
            digits[i].addActionListener( listener ); 
        }
        digits[10] = new JButton( "C" );
        digitsPanel.add( digits[10] );
        digits[10].addActionListener( listener ); 

        digits[11] = new JButton( "CE" );
        digitsPanel.add( digits[11] );
        digits[11].addActionListener( listener );       

        JPanel opsPanel = new JPanel();
        opsPanel.setLayout(new GridLayout(4,1));
        String[] opCodes = { "+", "-", "*", "/" };
        for (int i=0 ; i<4 ; i++ )
        {
            ops[i] = new JButton( opCodes[i] );
            opsPanel.add( ops[i] );
            ops[i].addActionListener( listener ); 
        }
        bottomPanel.add( digitsPanel );
        bottomPanel.add( opsPanel );

        content.add( topPanel );
        content.add( bottomPanel );

        window.setSize( 640,480);
        window.setVisible( true );
    }

    // We are again using an inner class here so that we can access
    // components from within the listener.  Note the different ways
    // of getting the int counts into the String of the label

    class ButtonListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            Component whichButton = (Component) e.getSource();
            // how to test for which button?
            // this is why our widgets are 'global' class members
            // so we can refer to them in here

            for (int i=0 ; i<10 ; i++ )
            {
                if (whichButton == digits[i])
                    expression.setText( expression.getText() + i );
            }



                    if (whichButton == ops[0]) 
                        expression.setText(expression.getText() + "+");
            if (whichButton == ops[1]) 
                expression.setText(expression.getText() + "-");
            if (whichButton == ops[2]) 
                expression.setText(expression.getText() + "*");
            if (whichButton == ops[3]) 
                expression.setText(expression.getText() + "/");

            if (whichButton == digits[10]) 
            {
                expression.setText("");
                result.setText("");
            }

            if (whichButton == digits[11]) expression.setText(expression.getText().substring(0, expression.getText().length() -1));

            if (whichButton == equals)
            {
                //if (expression.getText().contains("/0")) result.setText("DIVIDE BY ZERO ERROR");
                result.setText(evaluate());

        }
    }


            // need to add tests for other controls that may have been
            // click that got us in here. Write code to handle those

            // if it was the == button click then
            // result.setText( evaluate() );



        String evaluate()
        {
            if ( !isValid( expression.getText() )) return "INVALID"; // WRITE A ISVALID method
             // WRITE A ISVALID method

                String expr="4+5-12/3.5-5.4*3.14"; // replace with any expression to test
        System.out.println( "expr: " + expr );
        ArrayList<String> operatorList = new ArrayList<String>();
        ArrayList<Double> operandList = new ArrayList<Double>();
        // StringTokenizer is like an infile and calling .hasNext()
        StringTokenizer st = new StringTokenizer( expr,"+-*/", true );
        while (st.hasMoreTokens())
        {
            String token = st.nextToken();
            if ("+-/*".contains(token))
                operatorList.add(token);
            else
                operandList.add( Double.parseDouble( token) );
            }

        while(operandList.contains("*") || operandList.contains("/"))
        {
            int multiply = operandList.indexOf("*");
            int divide = operandList.indexOf("/");

            if(multiply<divide)
            {
                double quotients = (operandList.get(multiply)*operandList.get(multiply+1));
                operandList.set(multiply, quotients);
                operandList.remove(multiply+1);
                operandList.remove(multiply);
            }
            if(divide<multiply)
            {
                double products = (operandList.get(divide)/operandList.get(divide+1));
                operandList.set(divide, products);
                operandList.remove(divide+1);
                operandList.remove(divide);
            }

        }
        while(operandList.contains("+")||operandList.contains("-"))
        {
            int add = operandList.indexOf("+");
            int subtract = operandList.indexOf("-");

            if(add<subtract)
            {
                double adds = (operandList.get(add)+operandList.get(add+1));
                operandList.set(add, adds);
                operandList.remove(add+1);
                operandList.remove(add);
            }
            if(subtract<add)
            {
                double subs = (operandList.get(subtract)-operandList.get(subtract+1));
                operandList.set(subtract, subs);
                operandList.remove(subtract+1);
                operandList.remove(subtract);
            }
        }
        return (" " + operandList.get(0));

        }
        boolean isValid( String expr )
        {   

            if(expr.matches("[a-zA-Z]+")==false) return true; 
            else if(expr.startsWith("+")||expr.startsWith("-")||expr.startsWith("*")||expr.startsWith("/")==false) return true;
            else if(expr.endsWith("+")||expr.endsWith("-")||expr.endsWith("*")||expr.endsWith("/")==false) return true;
            if(expr.matches("[0-9]/0")==false) return true; 




            //test for no chars other than 0123456789+-*/
            //no operator at fornt of back of expr
            //no two ops in a row
            //no divide by zero
            //else return false
            else return false;
        }
    } // END BUTTON LISTNER
    public static void main(String [] args)
    {
        new SimpleCalc();
    }
}
import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
导入java.util.*;
公共类SimpleCalc
{
JFrame window;//包含所有内容的主窗口
容器内容物;
JButton[]位=新JButton[12];
JButton[]ops=新JButton[4];
JTextField表达式;
JButton等于;
JTextField结果;
公共SimpleCalc()
{
窗口=新JFrame(“简单计算”);
content=window.getContentPane();
setLayout(新的GridLayout(2,1));//2行,1列
ButtonListener侦听器=新建ButtonListener();
//顶部面板包含表达式字段、等号和结果字段
// [4+3/2-(5/3.5)+3]  =   [3.456]
JPanel-topPanel=新的JPanel();
setLayout(新的GridLayout(1,3));//1行,3列
表达式=新的JTextField();
expression.setFont(新字体(“verdana”,Font.BOLD,16));
表达式.setText(“”);
等于=新的JButton(“=”);
等于.setFont(新字体(“verdana”,Font.BOLD,20));
equals.addActionListener(listener);
结果=新的JTextField();
setFont(新字体(“verdana”,Font.BOLD,16));
result.setText(“”);
添加(表达式);
topPanel.add(等于);
添加(结果);
//底部面板包含左侧子面板中的数字按钮和右侧子面板中的操作员
JPanel bottomPanel=新的JPanel();
bottomPanel.setLayout(新的GridLayout(1,2));//1行,2列
JPanel digitsPanel=新的JPanel();
设置布局(新的网格布局(4,3));

对于(inti=0;i你是写代码还是从你朋友的家庭作业中抄来的

它写得很好:
String expr=“4+5-12/3.5-5.4*3.14”//替换为任何要测试的表达式


你永远不会在计算器上读取实际的表达式…你只是在使用常量值。

你有一个硬编码的表达式。
String expr=“4+5-12/3.5-5.4*3.14”每次都会进行计算。试试
String expr=expression.getText();
不过,答案应该是-11.38左右

Double.parseDouble()
的一个优点是它可以解析带有+或-符号的字符串。您可以将符号连接到数字,而忽略第二个列表

String evaluate(){
  if ( !isValid( expression.getText() )) return "INVALID";
  String expr = expression.getText();
  //String expr="4+5-12/3.5-5.4*3.14";
  System.out.println( "expr: " + expr );
  String [] dividedExpresions = expr.split("(?=[-|\\+])");  //split by + and -
  Double result = 0.0;
  for (String dividedExpresion:dividedExpresions){
      System.out.println(dividedExpresion);
      result += evaluateMultiplicativeExpression(dividedExpresion);
  }
  return result + "";
}
Double evaluateMultiplicativeExpression(String expression) {
    for(int i = expression.length() -1 ; i > 0 ; i--){
        if(expression.charAt(i) == '*'){
            return evaluateMultiplicativeExpression(expression.substring(0,i))
                * Double.parseDouble(expression.substring(i+1));
        }
        if(expression.charAt(i) == '/'){
            return evaluateMultiplicativeExpression(expression.substring(0,i))
                / Double.parseDouble(expression.substring(i+1));
        }
    }
    return Double.parseDouble(expression);
}

你的caps锁钥匙坏了吗?我很不愿意再加上caps…如果你已经解决了你的问题,最好给它添加一个答案并接受它,而不是把它嵌入问题本身。我现在确实设法让它工作了,我发现了一些简单的错误。谢谢你的帮助,当我被codi时,我很容易错过简单的事情很长一段时间。