简体   繁体   中英

How to apply a value from one method to another?

Cant set radius to count square: there're two methods, but how to force Java to count my square through radius that is random from randomNumber() ?

public class Figure {  

    public double randomNumber() {
        return Math.random() * 11;
    }
    public double circleArea () {
       return Math.PI*Math.pow(r,2); //how to assign a variable r in order to connect to randomNumber()??
    }

    public static void main(String[] args) {
        Figure figure = new Figure();
        System.out.println("r="+figure.randomNumber()+", s="+figure.circleArea());
    }

 }

Few different ways. You need to choose what works best for your scenario:

You can call the method from where required.

public double circleArea () {
   return Math.PI*Math.pow(randomNumber(),2);
}

You can change the method to include a variable.

public double circleArea (double r) {
   return Math.PI*Math.pow(r,2);
}
public static void main(String[] args) {
    Figure figure = new Figure();
    double r = figure.randomNumber();
    System.out.println("r=" + r + ", s=" + figure.circleArea(r));
}

All you have to do is defining a private variable that holds the r value

public class Figure {
private double r;
public double randomNumber() {
    r = Math.random() * 11;
    return r;
}
public double circleArea () {
   return Math.PI*Math.pow(r,2); //how to assign a variable r in order to connect to randomNumber()??
}

public static void main(String[] args) {
    Figure figure = new Figure();
    System.out.println("r="+figure.randomNumber()+", s="+figure.circleArea());
}

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