Your problem is the very typical indexOf(). It is usually a convention to return -1 when the element was not found, and the index (which is greater or equal to 0) otherwise.
You have different ways to get to that result.
Convert your array to a List
int numUser = Integer.parseInt(inputUser);
int index = Arrays.asList(sum).indexOf(numUser);
if (index < 0) {
System.out.println("The number is not in the array");
} else {
System.out.println("The number is in the array: " + index);
}
Use Apache ArrayUtils
int numUser = Integer.parseInt(inputUser);
int index = ArrayUtils.indexOf(sum, numUser);
if (index < 0) {
System.out.println("The number is not in the array");
} else {
System.out.println("The number is in the array: " + index);
}
Write it yourself
int numUser = Integer.parseInt(inputUser);
int index = -1;
for (int i = 0; i < sum.length; ++i) {
if (sum[i] == numUser) {
index = i;
break;
}
}
if (index < 0) {
System.out.println("The number is not in the array");
} else {
System.out.println("The number is in the array: " + index);
}
If you don't mind converting to a List
, I would use the first method (clearer code with least dependencies). If you do mind and are already using Apache Utils in your project, the second method is fine, and avoid the conversion. If you want to keep as little dependencies and are fine with more complex source code, the third method might be what you are after!