Ok I have been trying this exercise because I am not good at exceptions.So here is the context of the exercise:Write a class with main method(the following code is give by the task):
public class task{
public static void main(
String[] args)
{
int[] array = new int[10];
// initialise array
int result =task.min(array);
// Where the class task
// contains the min method
}
so I am asked to make sure that the method works even if the array contains only one element or none at all.So with the code give above I have to use exceptions to handle all the errors that could pop up.
This is what I did:
public static void main(String[] args){
int[] array = new int[10];
array[0]=5;
array[1]=7;
int result =Exercise1.min(array);
if(array.length<=0){
throw new IllegalArgumentException("empty array");
}
else if(array.length<10 && array.length>0){
throw new IllegalArgumentException("I got just these numbers");
}
System.out.println(result);
}
public static int min(int[] array) {
int min = array[0];
for(int i=1;i<array.length;i++){
if(array[i]< min){
min = array[i];
}
}
return min;
}
}
However no matter what I write the output is always 0 and I don't understand why.In case my approach is entirely wrong please offer some advice.