繁体   English   中英

具有不同长度乘法的Java数组

[英]Java arrays with different length multiplication

您好,我正在做一个项目,遇到一个我无法解决的问题。

我有3个数组,都是double ... hours [],rate [],prevHrs []。 我将小时和prevhrs复制到一个名为monthhours []的新数组中,现在我需要重新排列它,以便将Hours数组中的每个元素分别放置在正确的位置。 我需要prevhrs的前三个元素,然后是小时中的第一个元素,然后是prevhrs的4,5,6元素和小时的第二个元素,依此类推。 然后,在完成所有操作之后,我需要从新的monthHours数组中获取每个元素,并将其乘以rate数组中的元素。 基本上,rate [0]将乘以mountHours [0] [1] [2] [3],然后rate [1]乘以monthHours [4] [5] [6] [7]

如果有人可以帮助,将不胜感激。 到目前为止,这是我所需要的,我已经问过了全能的Google,但找不到我正在寻找的东西。

String [] names = {"Barry", "Lindsey", "Arron", "Brent"};
    double [] hours = {40.0, 37.5, 39.5, 18.5};
    double [] rate = {15.67, 8.90, 8.90, 12.33};
    double [] prevHrs = {32.0, 40.0, 39.0, 28.5, 31.5, 38.0, 40.0, 24.0, 36.0, 40.0, 40.0, 22.5};
    double [] monthHours = new double[16];
    double mostHours;
    mostHours =FinalMethods.getHighest(hours);
    double pay[] = FinalMethods.calculatePay(hours, rate);
    double totalPay[] = FinalMethods.calculateMonthpay(monthHours, rate);

    System.out.printf("The employee who Worked the most hours is %s" + " With %.2f" + "hours\n",names[0], mostHours);
    System.out.println(" ");
    System.out.println("Name \tHours \tRate \tTotal");
    for(int i=0;i<names.length;i++)
        System.out.printf(names[i] +"\t"+ hours[i] +"\t"+ rate[i] +"\t"+ pay[i]+"\n" );


    System.arraycopy(hours, 0, monthHours, 0, hours.length);
System.arraycopy(prevHrs, 0, monthHours, hours.length, prevHrs.length);

    System.out.println(" ");
    System.out.println("Employee Monthly Pay");
    System.out.println(" ");
    System.out.println("Name \tTotal");
    for(int i=0;i<names.length;i++)
        System.out.printf(names[i] +"\t"+ totalPay[i]+"\n" );


} 

    // Calculate Pay
            public  static double[] calculatePay(double[] hours, double[] rate){

                double[] pay = new double[hours.length];
                for (int i = 0; i < hours.length; i++) {
                        pay[i] = hours[i] * rate[i];
                }
                return pay;
            }
// Calculate Monthly Pay 
    public static double[] calculateMonthpay(double[] monthHours, double[] rate){

        double[] totalPay = new double[monthHours.length];
        for(int i = 0; i < monthHours.length; i++){
            totalPay[i] = monthHours[i] * rate[i] % rate[rate.length];
        }
            return totalPay;

}    

如果您走出了看似安全的数组领域,而跳入了面向对象编程的可怕深渊,则可以使您的生活变得更加轻松。

在这里,我持有一系列Employees并让他们计算自己的工资。

class Employee {

    final String name;
    final double hours;
    final double rate;
    final double[] prevHours;

    public Employee(String name, double hours, double rate, double[] prevHours) {
        this.name = name;
        this.hours = hours;
        this.rate = rate;
        this.prevHours = prevHours;
    }

    public String getName() {
        return name;
    }

    public double getHours() {
        return hours;
    }

    public double getRate() {
        return rate;
    }

    public double[] getPrevHours() {
        return prevHours;
    }

    public double getPay() {
        return rate * hours;
    }

    public double getMonthsPay() {
        double monthsPay = getPay();
        for (double h : prevHours) {
            monthsPay += rate * h;
        }
        return monthsPay;
    }

}

private Employee getMostHours(Employee[] employees) {
    Employee most = null;
    for (Employee employee : employees) {
        if (most == null || employee.getHours() > most.getHours()) {
            most = employee;
        }
    }
    return most;
}

public void test() {
    System.out.println("Hello");
    Employee[] employees = {
        new Employee("Barry", 40.0, 15.67, new double[]{32.0, 40.0, 39.0}),
        new Employee("Lindsey", 37.5, 8.90, new double[]{28.5, 31.5, 38.0}),
        new Employee("Arron", 39.5, 8.90, new double[]{28.5, 31.5, 38.0}),
        new Employee("Brent", 18.5, 12.33, new double[]{28.5, 31.5, 38.0})};
    Employee mostHours = getMostHours(employees);
    System.out.printf("The employee who Worked the most hours is %s" + " With %.2f" + "hours\n", mostHours.getName(), mostHours.getHours());
    System.out.println();
    System.out.println("Name \tHours \tRate \tTotal \tMonth");
    for (Employee employee : employees) {
        System.out.println(employee.getName()
                + "\t" + employee.getHours()
                + "\t" + employee.getRate()
                + "\t" + employee.getPay()
                + "\t" + employee.getMonthsPay());
    }
}

我同意面向对象的编程方法更好,但是由于有人要求它可以手动执行,因此我为第一个用例写了一个小例子。

因此,这是通过添加3个元素,然后再添加1个其他元素来组合数组。 它不是很漂亮,但是希望可以说明一下这个想法:

public static void main(String[] args) {
        double [] hours = {40.0, 37.5, 39.5, 18.5};
        double [] prevHrs = {32.0, 40.0, 39.0, 28.5, 31.5, 38.0, 40.0, 24.0, 36.0, 40.0, 40.0, 22.5};

        // 3 elements of prevHrs, 1 element of hours
        int newSize = hours.length + prevHrs.length;
        double[] combinedArray = new double[newSize];

        int prevHrsOffset = 0;

        for(int i= 0; i < hours.length; i++) {

            for( int j=0; j<3; j++) { // 3 elements
                combinedArray[i+prevHrsOffset] = prevHrs[prevHrsOffset];
                prevHrsOffset ++;

                // TODO insert safety check for arrayoutofbounds
            }

            combinedArray[i+prevHrsOffset] = hours[i];
        }


        for(int i=0; i < combinedArray.length; i++) {
            System.out.println(combinedArray[i]);
        }

    }

输出为:

32.0, 40.0, 39.0, 40.0, 28.5, 31.5, 38.0, 37.5, 40.0, 24.0, 36.0, 39.5, 40.0, 40.0, 22.5, 18.5

注意,这不是一个非常安全的方法,您必须防止索引违规等。

您可以使用列表进行添加(至少以这种方式索引不是问题)。

同样,小时数和上一个小时的长度可能会有所不同,因此组合将不再起作用。

希望能回答您的问题,并为您提供一个解决方法。

以类似方式计算总工资:

double [] rate = {15.67, 8.90, 8.90, 12.33};
        double[] totalPay = new double[newSize]; // the total pay based on that other array
        int combinedArrayOffset = 0;
        for (int i = 0; i < rate.length; i++) {

            for (int j = 0; j < 4; j++) { // 4 elements
                totalPay[combinedArrayOffset] = rate[i] * combinedArray[combinedArrayOffset];
                combinedArrayOffset++;
                // TODO insert safety check for arrayoutofbounds
            }
        }

        System.out.println("total pay:");

        for(int i=0; i < totalPay.length; i++) {
            System.out.print(totalPay[i] + ", ");
        }

我强烈建议您像已经建议的那样习惯于面向对象的编程,但是由于您在当前代码中寻求帮助,因此这是我的解决方案-用“看似安全的数组基础”编写:

码:

public class FinalMethods {
    public static void main(String[] args) {
        String[] names = {"Barry", "Lindsey", "Arron", "Brent"};
        double[] hours = {40.0, 37.5, 39.5, 18.5};
        double[] rate = {15.67, 8.90, 8.90, 12.33};
        double[] prevHrs = {
                32.0, 40.0, 39.0,
                28.5, 31.5, 38.0,
                40.0, 24.0, 36.0,
                40.0, 40.0, 22.5
        };
        double[] monthHours;
        {
            // we have name.length employees, and for each 3 prevHrs entries and 1 hours entry
            monthHours = new double[names.length * 4];
            for (int i = 0; i < names.length; i++) {
                // append/copy range of 3 prevHrs entries to monthHours
                System.arraycopy(prevHrs, i * 3, monthHours, i * 4, 3);
                // append/copy range of 1 hours entries to monthHours
                System.arraycopy(hours, i, monthHours, i * 4 + 3, 1);

                // equivalent to:
                /*
                    monthHours[i * 4] = prevHrs[i * 3];
                    monthHours[i * 4 + 1] = prevHrs[i * 3 + 1];
                    monthHours[i * 4 + 2] = prevHrs[i * 3 + 2];
                    monthHours[i * 4 + 3] = hours[i];
                */
            }
        }
        int mostHoursIndex = FinalMethods.getHighest(hours);
        double pay[] = FinalMethods.calculatePay(hours, rate);
        double totalPay[] = FinalMethods.calculateMonthPay(monthHours, rate);

        // most worked
        System.out.printf("The employee who worked most hours is %s with %.2f hours\n", names[mostHoursIndex], hours[mostHoursIndex]);

        System.out.println();

        // print pay table
        System.out.println("\n-- Employee Pay --\n");
        System.out.printf("%-10s %-10s %-10s %-10s\n", "Name", "Hours", "Rate", "Total");
        System.out.println();
        for (int i = 0; i < names.length; i++) {
            System.out.printf("%-10s %-10.2f %-10.2f %-10.2f\n", names[i], hours[i], rate[i], pay[i]);
        }

        System.out.println();

        // print monthly pay table
        System.out.println("\n-- Employee Monthly Pay --\n");
        System.out.printf("%-10s %-10s\n", "Name", "Total");
        System.out.println();
        for (int i = 0; i < names.length; i++) {
            System.out.printf("%-10s %-10.2f\n", names[i], totalPay[i]);
        }
    }

    public static int getHighest(double... values) {
        // result will be -1 for empty arrays
        int result = -1;
        // EVERY value should be > max when starting, thus:
        double max = Double.NEGATIVE_INFINITY;
        for (int i = 0; i < values.length; i++) {
            double value = values[i];
            if (value > max) {
                // found a higher entry, mark index and update max
                max = value;
                result = i;
            }
        }
        // return index of highest entry
        return result;
    }

    public static double[] calculatePay(double[] hours, double[] rate) {
        double[] result = new double[rate.length];
        // for each employee
        for (int i = 0; i < result.length; i++) {
            // sum his hours (1 entry) * his rate
            result[i] = hours[i] * rate[i];
        }
        return result;
    }

    public static double[] calculateMonthPay(double[] monthHours, double[] rate) {
        double[] result = new double[rate.length];
        // for each employee
        for (int i = 0; i < result.length; i++) {
            // sum his monthHours (4 entries) * his rate
            double monthPay = 0;
            for (int j = 0; j < 4; j++) {
                monthPay += monthHours[i * 4 + j] * rate[i];
            }

            result[i] = monthPay;
        }
        return result;
    }
}

输出:

The employee who worked most hours is Barry with 40,00 hours


-- Employee Pay --

Name       Hours      Rate       Total     

Barry      40,00      15,67      626,80    
Lindsey    37,50      8,90       333,75    
Arron      39,50      8,90       351,55    
Brent      18,50      12,33      228,11    


-- Employee Monthly Pay --

Name       Total     

Barry      2366,17   
Lindsey    1205,95   
Arron      1241,55   
Brent      1491,93   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM