Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing object values to methods

Tags:

java

I am trying to make a void method that calculates average, but I would like to pass values to the method from the main method. Here is an example of what I am trying to do:

 public class Plant {

    int leaves;
    int age;
    int sumLeaves;
    double average;

    void averageLeaves() {

        sumLeaves = leaves + leaves; //here is where I need help
        average = (double) sumLeaves / 2;
        System.out.println("The average number of leaves is: " + average);

    }

    public static void main(String[] args) {

        Plant plantA = new Plant();
        plantA.leaves = 5;

        Plant plantB = new Plant();
        plantB.leaves = 3;

        averageLeaves();

    }

The problem I'm having is getting the values of multiple plants into the method. I've tried using .get, loops, static, and many other things and haven't figured it out yet. What I want is to the value of plantA.leaves and plantB.leaves to the method in order to find their sum.

like image 785
Matthew A Avatar asked Sep 27 '22 13:09

Matthew A


1 Answers

Since you have the averageLeaves() defined in the Plant class, You have to actually invoke the methode from one of the plant instance. Here is how you should do it.

plantA.averageLeaves();

One big mistake you are doing here is,

sumLeaves = leaves + leaves;         

This actually adds the leaves of a specific (one) instance of plants, It is wrong. you have to actually pass the number of leaves from difference instances.

Here is a nicer way to do it using getters & setters. Also it would make much sense to make the averageLeaves() method static. That way you do not need an instance to invoke the method.

    public class Plant {

    int leaves;
    int age;
    //int sumLeaves;  you do not need them now, as the averageLeaves method is static
    //double average;

    static void averageLeaves (int leaves1, int leaves2) {

        int sumLeaves = leaves2 + leaves1;               //here is where I need help
        double average = (double) sumLeaves / 2;
        System.out.println("The average number of leaves is: " + average);
    }

    void setLeaves(int leaves){
        this.leaves = leaves;
    }

    int getLeaves(){
        return this.leaves;
    }
}

    public class Main {

    public static void main(String[] args) {

        Plant plantA = new Plant();
        plantA.setLeaves(5);

        Plant plantB = new Plant();
        plantB.setLeaves(3);

        Plant.averageLeaves(plantA.getLeaves(), plantB.getLeaves());
    }
}
like image 155
Fawzan Avatar answered Nov 02 '22 23:11

Fawzan