首页 > 解决方案 > java - 如何在一种方法中将多个进程返回给java中的main方法

问题描述

是否可以在一种方法中进行多个计算并将数组的所有值返回以再次发送到另一种将打印/显示它们的方法

也就是main方法中的调用语句

process_g(rate, hours, overtime, emp_num);

我会将这些变量的值发送到一个方法并再次调用它们,并且emp_num是数组大小。

也就是工艺方法

public static double process_g(double rate[], double hours[],double overtime[], int emp_num)
 {
   double STtax = 0, FEDtax = 0, union = 0, net = 0, Tgross = 0, Agross = 0, repeat = 999;
   double[]gross = new double[emp_num];
  for(int i = 0; i < emp_num; i++)
  {
    gross[i] = (rate[i] * hours[i]) + overtime[i];
    STtax = gross[i] * 0.06;
    FEDtax = gross[i] * 0.12;
    union = gross[i] * 0.01;
    net = gross[i] - (STtax + FEDtax + union);
    Tgross = Tgross + gross[i];
    Agross = Tgross / (i+1);
  }
 }

将数组值发送到主要方法后,我想将它们发送到另一个打印它们的方法。

所以我在main方法中写了这个

output(emp_num, emp1, emp2, emp3, hours, rate, overtime, gross, STtax, FEDtax, union, net, Tgross, Agross);

所有输入都已声明并更正我唯一的问题是返回并调用process_g主方法中的方法

标签: javaarraysmethods

解决方案


定义输出数组以匹配输入数组

如果您想以基于数组的方式工作,则调用方法除了已经为输入定义的数组外,还应该为输出定义数组。将这些输出数组与输入数组一起传递。

// Inputs
int countOfEmployees = … ;
double rate[] = … ;   // Declare and populate.
double hours[] = … ;  // Declare and populate.
…

// Outputs 
double stTax[] = new double[ countOfEmployees ] ;   // Declare, but do *not* populate. Will be populated by the method called below.
double fedTax[] = new double[ countOfEmployees ] ;  // Declare, but not populate.

this.process_g( rate , hours , … , stTax , fedTax , … ) { … }

// Report. The output arrays have now been populated by the called method.
for( int i = 0 ; i < emp_num ; i++ )
{
    String result = "Hours: " = hours[ i ] + " stTax: " + stTax[ i ] ) ;
}

// Or pass them to another method.
this.someOtherMethod( rate , hours , … , stTax , fedTax ) ;

顺便说一句,您似乎忘记在数据模型中包含员工标识符。在您的示例中,我们不知道哪个员工在输入数据的哪一行工作。

改为使用对象

基于数组的方法在非 OOP 编程环境中很常见。但是您没有利用 Java面向对象的强大功能。

我建议您创建一个名为PayPeriod. 该类将具有用于输入和结果的成员字段。输入将传递给构造函数,一次一个支付周期。计算结果字段的方法将包含在PayPeriod类中,可能从构造函数中调用。

public class PayPeriod 
{
    // Member fields
    final double rate ;
    final double hours ;
    double stTax ;
    double fedTax ;

    public PayPeriod( double rate , double hours , … ) 
    {
        // Inputs
        this.rate = Objects.requireNonNull( rate ) ;
        this.hours = Objects.requireNonNull( hours ) ;
        …
        // Calculate results
        this.stTax = … ;
        this.fedTax = … ;
    }

}

PayPeriod在实例化时将对象收集到列表或集合中。

BigDecimal

顺便说一句,永远不要使用doubleor Double, or float/ Float,来赚钱。对于您关心准确性的任何情况,请使用BigDecimal,从不使用浮点类型。浮点技术牺牲了执行速度的准确性。


推荐阅读