Search code examples
javaarrayscustom-exceptions

Exceptions (Java)


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.


Solution

  • int[] array = new int[10];

    This line of code sets 10 places of the array "array", all equal to "0".

    In order for min to not return 0 you need to set all the values of the array or change the size to 2.

    Setting them could easily be done with this function:

    for(int i = 0; i < array.length; i++){
        array[i] = i + 1;
    }
    

    This will set all the values of the array so you can remove this code:

    array[0]=5;
    array[1]=7;
    

    Setting these will fix your min value always being 0.

    It will always be 1 if you use my suggested loop.