如何获取方法的输出并传递给JAVA中的另一个方法?

时间:2015-12-13 11:14:54

标签: java methods

我是java的新手,还在学习这些概念。从下面的代码我有两种方法,一种用于儿童,一种用于成人。我想输出总人数,所以我想要第三个方法(calc_total),它将获取calc_children和calc_adults的输出。我无法弄清楚如何做到这一点,有人能指出我正确的方向吗?

public class Testcalc {

    public int calc_children( int aBoys, int aGirls) {
        int a_num_children = aBoys + aGirls;

        return a_num_children;
    }   

    public int calc_adults( int aMen, int bWomen) {
        int a_num_adults = aMen + bWomen;

        return a_num_adults;
    }

    public static void main(String[] args) {    

        Testcalc calc1 = new Testcalc();

        int aChildren = calc1.calc_children(4,6);
        int bAdults = calc1.calc_adults(5,8);

        System.out.println("Total Children " + aChildren);
        System.out.println("Total Adults " + bAdults);  
    }                               
}

5 个答案:

答案 0 :(得分:0)

public int myMethod(){
  return 5;
}

public void myAge(int age){
  System.out.println(age);
}

//You can do:
myAge(myMethod());

在你的情况下:

public int calcTotal(int children, int adults){
 return children + adults;
}


//You can do:
calcTotal(calc_children(5,10),calc_adults(9,12));

答案 1 :(得分:0)

很简单,你已经有了这种方法,将这个方法添加到Testcalc

public int calc_total( int totalMen, int totalWomen) {
    int a_num_total= totalMen+ totalWomen;

    return a_num_total;
    }

然后:

public static void main(String[] args) {

Testcalc calc1 = new Testcalc();

int aChildren = calc1.calc_children(4,6);
int bAdults = calc1.calc_adults(5,8);
int total = calc1.calc_total(aChildren,bAdults);

System.out.println("Total Children " + aChildren);
System.out.println("Total Adults " + bAdults);  
System.out.println("Grand total " + total);
} 

答案 2 :(得分:0)

你可以像你提到的那样提出第三种方法calc_total,就像你的其他两种方法一样,它也可以使用两个ints作为参数。然后在您的主文件中,您可以传递calc_childrencalc_adults的结果作为传递给新方法calc_total的参数。想一想。使用aChildrenbAdults

答案 3 :(得分:0)

你可以这样做:

  public int calc_total(){
    Testcalc calc1 = new Testcalc();

   int total= calc1.calc_children(4,6) + calc1.calc_adults(5,8);

   return total;
 }

答案 4 :(得分:0)

public class Testcalc
{

    public class Testcalc {

    public int calc_children( int aBoys, int aGirls) {
        int a_num_children = aBoys + aGirls;

        return a_num_children;
    }   

    public int calc_adults( int aMen, int bWomen) {
        int a_num_adults = aMen + bWomen;

        return a_num_adults;
    }
    public int calc_total(int a,int b)
    {
return a+b;
}

    public static void main(String[] args) {    

        Testcalc calc1 = new Testcalc();

      int aChildren = calc1.calc_children(4,6);
     int bAdults = calc1.calc_adults(5,8);
    int total=calc1.calc_total(aChildren,bAdults);

        System.out.println("Total Children " + aChildren);
        System.out.println("Total Adults " + bAdults);  
    System.out.println("Total" + total);

    }                               
}

传递变量" aChildren"和" b成人"到返回其总和的新函数。返回的值将被赋值给变量" total"。简单地打印变量" total"。