1
//Square root of a no. using command line argument
class Calculator {
    double i;
    double x = Math.sqrt(i);
}

class SquareRoot {
    public static void main(String arg[]) {
        Calculator a = new Calculator();
        a.i = Integer.parseInt(arg[0]);
        System.out.println("The square root of " + a.i + " is " + a.x);
    }
}

My Output:

The square root of 64 is 0.0

What's wrong with my code?

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Aps
  • 13
  • 5

1 Answers1

0

try this :

class Calculator {
    double i, x;
    void squareRoot() {
        x = Math.sqrt(i);
    }
}

class SquareRoot {
    public static void main(String arg[]) {
        Calculator a = new Calculator();
        a.i = Integer.parseInt(arg[0]);
        a.squareRoot();
        System.out.println("The square root of " + a.i + " is " + a.x);
    }
}
pratik patel
  • 306
  • 5
  • 16
  • So without using squareRoot() method i can't do it directly?Can you explain it further? – Aps Feb 01 '20 at 05:23
  • in your code `Math.sqrt(i)` execute before getting a value of variable a. your x's value is set when you are creating object of `calculator` class. which is executed before getting value of a.that's why you need to call squareroot function after getting value of i. – pratik patel Feb 01 '20 at 05:26