patternjavaMinor
Finding array indices that add up to another number
Viewed 0 times
indicesnumberarraythatanotherfindingadd
Problem
I'm writing a method that takes (1) an array of
Is there a better way to write this method that does not violate the coding standards mentioned above?
The coding standards I was looking at are located here.
ints and (2) an int. The purpose of the method is to find the indices of the two numbers in the array that add up to the value passed in as the second parameter to the method (sum) and return those values in an int[]. Exactly two numbers in the passed in array will add up to "sum", so as soon as they are identified the method should finish. I have come up with two solutions so far, but both seem ugly to me://this method is bad because it has multiple returns
private int[] findIndexes(int[] intAr, int sum) {
for (int i = 0; i < intAr.length; ++i) {
for (int k = i + 1; k < intAr.length; ++k) {
if(intAr[i] + intAr[k] == sum) {
return new int[] {i + 1, k + 1};
}
}
}
//should never reach here
return null;
}
//this method is bad because it uses "break" outside of a switch statement
private int[] findIndexes(int[] intAr, int sum) {
int[] indexAr = new int[2];
outer:
for (int i = 0; i < intAr.length; ++i) {
for (int k = i + 1; k < intAr.length; ++k) {
if(intAr[i] + intAr[k] == sum) {
indexAr[0] = i + 1;
indexAr[1] = k + 1;
break outer;
}
}
}
return indexAr;
}Is there a better way to write this method that does not violate the coding standards mentioned above?
The coding standards I was looking at are located here.
Solution
There's nothing wrong with a break statement used outside a switch statement. (2nd example)
If a professor or some other authority figure is enforcing that rule, that's a pain, but the code is perfectly fine. There's even a similar example in the Java Tutorials on Branching
If a professor or some other authority figure is enforcing that rule, that's a pain, but the code is perfectly fine. There's even a similar example in the Java Tutorials on Branching
Context
StackExchange Code Review Q#3813, answer score: 5
Revisions (0)
No revisions yet.