As the title says I just need some help/advice on how I can simplify a part of my code. I get the output I want but it's obvious to see that the way I go about it is a bit excessive. What I'm trying to do in my program is pass the array
int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};
Into my buildFeetArray
method which just takes the array elements, divides them by 12 to get a new element value which is then put in a new array which is returned. Here is the method
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;
}
Ideally the output should be
int length = 8;
[0] = 1;
[1] = 2;
[2] = 1;
[3] = 1;
[4] = 1;
[5] = 2;
[6] = 2;
[7] = 2;
Which it is but there's definitely an easier way to go about it, if possible I'd like to avoid using lists and sticking with loops as I need practice with them. Thank you in advance for any advice/tips.
I wrote some pseudo-code for this, in which you have to just initialize an array and increment particular index of array when a certain condition matches:
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;
}
You may want to use another array to store the result, e.g :
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;
}
What about this:
int[] lessThanArray = new int[8];
for (int entry: myInches) {
int lessThan = entry / 12;
if (lessThan < 8) {
lessThanArray[lessThan]++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With