简体   繁体   English

计算器 - setText(String)不适用于双打

[英]Calculator - setText(String) doesn't work with Doubles

So I am trying to make a calculator and I am using JFrame code and trying to use the built in Math to find the square root of a number. 所以我正在尝试制作一个计算器,我正在使用JFrame代码并尝试使用内置的Math来查找数字的平方根。 The code below is where I am having issues. 下面的代码是我遇到问题的地方。 "display.setText(Math.sqrt(Double.parseDouble(display.getText())));" “display.setText(Math.sqrt(Double.parseDouble(display.getText())));”

gives me the error of "The method setText(String) in the type JTextComponent is not applicable for the arguments (double)" 给我错误“JTextComponent类型中的方法setText(String)不适用于参数(double)”

    sqrt = new JButton("SQRT");
    sqrt.setBounds(298, 141, 65, 65);
    sqrt.setBackground(Color.BLACK);
    sqrt.setForeground(Color.BLACK);
    sqrt.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            setTempFirst(Double.parseDouble(display.getText()));
            display.setText(Math.sqrt(Double.parseDouble(display.getText())));
            operation[5] = true;

        }
    });
    add(sqrt);

Since Math.sqrt returns a double you can not do: 由于Math.sqrt返回一个double,你不能这样做:

display.setText(Math.sqrt(Double.parseDouble(display.getText())));

instead you can use the value returned by that method and use the String.valueOf() like: 相反,您可以使用该方法返回的值并使用String.valueOf()如:

display.setText(String.valueOf(Math.sqrt(....

As you said, this method is expecting String instead of double, so you should convert result of 正如你所说,这个方法期望String而不是double,所以你应该转换结果

Math.sqrt(Double.parseDouble(display.getText()))

to double, eg: 加倍,例如:

String.valueOf(Math.sqrt(Double.parseDouble(display.getText())))

or 要么

Math.sqrt(Double.parseDouble(display.getText()))+""

Better way will be formatting this result to some decimal places, eg: 更好的方法是将此结果格式化为一些小数位,例如:

String.format( "%.2f", YOUR_NUMBER ) . String.format( "%.2f", YOUR_NUMBER )String.format( "%.2f", YOUR_NUMBER )

display.setText(Math.sqrt(Double.parseDouble(display.getText())));

should be 应该

display.setText(Math.sqrt(Double.parseDouble(display.getText())).toString());

Because you need String representation of sqrt. 因为您需要sqrt的String表示。 setText() cannot take Double setText()不能取Double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM