I have a nested loop that loops through every element in the list comparing it/sorting it , then I am trying to square the numbers in the list(keep in mind they need to be sorted). The problem is when I run my program, the 'test' array list that I am using does not print the last one squared, but it prints the second to last one squared twice. For example, if my array list is (1,2,3,4,5) my code should print (1,4,9,16,25) but instead it prints (1,4,9,16,16). I can't seem to figure out why.
My code:
public static void sortSquares(List<Integer> tempList) {
int result = 0;
for (int i = 0; i < tempList.size(); i ) {
for (int j = tempList.size() - 1; j > i; j--){
if (tempList.get(i) > tempList.get(j)) {
result = tempList.get(j) * tempList.get(j);
}
else if (tempList.get(j) > tempList.get(i)) {
result = (tempList.get(i) * tempList.get(i));
}
}
System.out.println(result);
}
}
CodePudding user response:
In the last external loop when i = 4
, the inner loop becomes:
for (int j = 4; j > 4; j--)
which does nothing, and the outer loop prints result
, which contains the previous value (16).
The solution could be to replace the condition for the inner loop to j >= i
. You also need to replace the condition of the if
, as tempList.get(j)
will now be equal to tempList.get(i)
:
for (int i = 0; i < tempList.size(); i ) {
for (int j = tempList.size() - 1; j >= i; j--){
if (tempList.get(i) > tempList.get(j)) {
result = tempList.get(j) * tempList.get(j);
}
else if (tempList.get(j) >= tempList.get(i)) {
result = (tempList.get(i) * tempList.get(i));
}
}
System.out.println(result);
}
It will work for (1,2,3,4,5).
That being said, the same result could be attained with a simpler code:
Collections.sort(tempList); /* Optional, if you want to sort the result */
for (int i = 0; i < tempList.size(); i ) {
System.out.println(tempList.get(i) * tempList.get(i));
}
CodePudding user response:
Solution won't work if tempList[i] == tempList[j]
.Replace else if
with else
and it will work.