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 inline math to find the square root of a number. Below is the code where the problems occur. "Display.setText (Math.sqrt (Double.parseDouble (display.getText ())));"

gives me the error "Method setText (String) in type JTextComponent is not applicable for 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);

      

+3


source to share


3 answers


Since Math.sqrt returns double, you cannot do:

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

      



instead, you can use the value returned by this method and use String.valueOf()

like:

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

      

+2


source


As you said, this method expects a String instead of a double, so you must convert the result

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

to double, for example:

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



or

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

The best way would be to format this result to some decimal places, for example:

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

...

0


source


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

      

it should be

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

      

Because you need the sqrt string representation. setText () cannot acceptDouble

0


source







All Articles