Math.Sqrt(x); not working?

I’m making a calculator and when trying to make the square root function, it outputs the number you put in, not the square root. Here’s the bit of code that applies to the square root function.

SquareRoot = (Button)findViewById(R.id.SquareRoot);
        SquareRoot.setOnClickListener(new OnClickListener() {
             public void onClick(View v) {
                x = TextBox.getText();
                xconv = Double.parseDouble(x.toString());
                Math.sqrt(xconv);
                answer = Double.toString(xconv);
                TextBox.setText(answer);
 
        }});

Just to give some information on this, x is a CharSequence, xconv is x converted to double, and answer is a string value. Thanks.

Edit: I have got the following resolution from Scaler, but still unsure about it as I’m a beginner. Need someone’s insights into it.

 SquareRoot = (Button)findViewById(R.id.SquareRoot);
    SquareRoot.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
            x = TextBox.getText();
            xconv = Double.parseDouble(x.toString());
            xconv = Math.sqrt(xconv);//======> you are not initalize the answer to a variable here
            answer = Double.toString(xconv);
            TextBox.setText(answer);
 
    }});

That is what it appears to be coded to do…

Hint with Processing Java:

References:

:)

2 Likes

Java uses ‘pass by value’ parameters this means that the above code means

calculate and return the square root of the ‘value’ of xconv

The value stored in the actual parameter xconv is never changed so the actual result has to be assigned to a variable . Hence

xconv = Math.sqrt(xconv);

Which means
calculate and return the square root of the ‘value’ of xconv THEN assign the returned value to xconv

2 Likes