Reputation: 41
I got my main task to work (rough translation):
Write a method, which returns the smallest number from a 1d array of integers.
Now i have to do a side task (rough translation):
Add an if statement to check if the array is null or empty, and if it is, return 0.
method:
public static int smallestNumber (int[] array1) {
int smallest = array1[0];
if (array1 == null || array1.length == -1) {
return 0;
}
else {
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
}
return smallest;
}
main:
public static void main(String[] args) {
int[] tab1 = {}; //empty array?
int smallestNumber = smallestNumber(tab1);
System.out.printf("The smallest number is: %d", smallestNumber);
}
The method works if i only check for null. But i'm confused why it wont work on empty array.
int[] tab1 = {};
EDIT: I also tried with array1.length == 0;
Upvotes: 3
Views: 377
Reputation: 45
public static int smallestNumber (int[] array1) {
if (array1 == null || array1.length == 0) {
return 0;
}
int smallest = array1[0];
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
return smallest;
}
Upvotes: 1
Reputation: 3605
Try checking for null first, as it is safer to check for that first. You also can use the method isEmpty() for the length.
public static int smallestNumber (int[] array1) {
if (array1 == null) {
return 0;
}
if (array1.isEmpty()) {
return 0;
}
int smallest = array1[0];
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
return smallest;
}
or add this as an alt:
public static int smallestNumber (int[] array1) {
if (array1 != null) {
if (array1.isEmpty()) {
return 0;
}
int smallest = array1[0];
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
return smallest;
} else {
return 0;
}
}
Upvotes: 1
Reputation: 16908
Firstly, Arrays are of non-negative size so array1.length
cannot be -1, instead make the comparison with 0
.
Secondly, the assignment int smallest = array1[0];
tries to access 0th position of an empty array which will result in java.lang.ArrayIndexOutOfBoundsException
.
So in conclusion move the assignment to smallest
in the else block and check the condition for empty or null array before you try to access any array value.
public static int smallestNumber (int[] array1) {
int smallest;
if (array1 == null || array1.length == 0) {
return 0;
}
else {
smallest = array1[0];
for (int element : array1) {
if (element < smallest) {
smallest = element;
}
}
}
return smallest;
}
Upvotes: 3