3

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);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Max E
  • 43
  • 2
  • [`NumberFormater.getNumberInstance().format(Math.sqrt(Double.parseDouble(display.getText())))`](https://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html) – MadProgrammer May 23 '17 at 22:25

3 Answers3

2

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(....
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

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

Mateusz Stefaniak
  • 856
  • 1
  • 9
  • 20
0
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

jas97
  • 29
  • 7
  • `Math.sqrt` returns primitive, so it doesn't have a `toString` method, which I'd consider poor practice anyway, given the alternatives – MadProgrammer May 23 '17 at 22:27