很确定我过度复杂化了我的循环,但不确定如何简化[封闭]

2022-09-04 05:09:17

正如标题所说,我只需要一些帮助/建议,了解如何简化代码的一部分。我得到了我想要的输出,但很明显,我这样做的方式有点过分。我试图在我的程序中做的是传递数组

int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};

在我的方法中,它只取数组元素,将它们除以12以获得一个新的元素值,然后将其放入返回的新数组中。这是方法buildFeetArray

 public static int[] buildFeetArray(int[] arrayParam) {
    int sum = 0;
    int lessthan1 = 0;
    int lessthan2 = 0;
    int lessthan3 = 0;
    int lessthan4 = 0;
    int lessthan5 = 0;
    int lessthan6 = 0;
    int lessthan7 = 0;
    int lessthan8 = 0;
    for (int count = 0; count < arrayParam.length; count++) {
        if (arrayParam[count] / 12 == 0) {
            lessthan1++;
        } else if (arrayParam[count] / 12 == 1) {
            lessthan2++;
        } else if (arrayParam[count] / 12 == 2) {
            lessthan3++;
        } else if (arrayParam[count] / 12 == 3) {
            lessthan4++;
        } else if (arrayParam[count] / 12 == 4) {
            lessthan5++;
        } else if (arrayParam[count] / 12 == 5) {
            lessthan6++;
        } else if (arrayParam[count] / 12 == 6) {
            lessthan7++;
        } else if (arrayParam[count] / 12 == 7) {
            lessthan8++;
        }
    }
    int[] newArray = {lessthan1, lessthan2, lessthan3, lessthan4, lessthan5, lessthan6, lessthan7, lessthan8};
    return newArray;
}

理想情况下,输出应为

int length = 8;
[0] = 1;
[1] = 2;
[2] = 1;
[3] = 1;
[4] = 1;
[5] = 2;
[6] = 2;
[7] = 2;

是的,但肯定有一种更简单的方法可以做到这一点,如果可能的话,我想避免使用列表并坚持循环,因为我需要练习它们。提前感谢您提供的任何建议/提示。


答案 1

我为此编写了一些伪代码,其中您只需要初始化一个数组,并在某个条件匹配时递增数组的特定索引:

public static int [] buildFeetArray(int [] arrayParam) {
    int index;
    int [] lessthan = {0,0,0,0,0,0,0,0};
    for (int count = 0; count < arrayParam.length; count++) {
        index = arrayParam[count]/12;
        if(index < 8 ) {
            lessthan[index]++;
        }
    }
    return lessthan;
}

答案 2

您可能希望使用另一个数组来存储结果,例如:

public static  int[] buildFeetArray(int [] arrayParam) {

    int[] lessThanArray = new int[8];

    for (int count = 0; count < arrayParam.length; count++) {
        for (int remainder = 0; remainder < lessThanArray.length; remainder++) {

            if (arrayParam[count] / 12 == remainder) {

                lessThanArray[remainder]++;
                break; // exit from the inner "for" loop
            }
        }
    }

    return lessThanArray;
}