小编Mat*_*w A的帖子

将对象值传递给方法

我试图制作一个计算平均值的void方法,但我想将值从main方法传递给方法.这是我想要做的一个例子:

 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();

    }
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是将多种植物的价值纳入方法中.我已经尝试过使用.get,循环static等许多其他东西,但还没有弄明白.我想要的是plantA.leavesplantB.leaves方法的价值,以找到他们的总和.

java

5
推荐指数
1
解决办法
93
查看次数

标签 统计

java ×1