简体   繁体   中英

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. The code below is where I am having issues. "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)"

    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:

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

instead you can use the value returned by that method and use the String.valueOf() like:

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

As you said, this method is expecting String instead of double, so you should convert result of

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 ) .

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. setText() cannot take Double

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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