Frage

Hello there stackoverflow users, im trying to initialize and fill my arrays with numbers and then find the max value of it, but when i start to fill array i get zeros or samenumbers which i input or ArrayIndexOutOfBoundsException or array stops with fill, i tryed few days but i really dont know what to do now, i have logical mistakes, please help.

public class Solution
{
    public static void main(String[] args) throws Exception
    {
        int[] array = initializeArray();
        int max = max(array);
        System.out.println(max);
    }
    public static int[] initializeArray() throws IOException {


        Scanner in = new Scanner(System.in);

        int Numbers[] = new int[5];

        if (in.hasNext())
        {
        for(int NumCntr = 0 ; NumCntr< Numbers.length ;NumCntr++)
        {
            Numbers[NumCntr] = in.nextInt();


        }
            System.out.println(Numbers);

        }

        return Numbers;
    }


    public static int max(int[] array) {


        int maxt = 0;

        for(int i=0;i < 5;i++)
        {
            if(array[i] >  array[i+1])
                maxt = array[i];
        }


        return maxt;




    }
}
War es hilfreich?

Lösung

The array size is 5 but at below loop for max value of i you are incrementing it by 1, and so trying to access array[5] (array[4+1]), which causes your ArrayIndexOutOfBoundsException.

     for(int i=0;i < 5;i++)
            {
                if(array[i] >  array[i+1])
--------------------------------------^
                    maxt = array[i];
            }

Andere Tipps

Change your 'max' method to this. You are comparing each row with the next one. e.g. 5,3,2,4,1 would end up as 4. You need to store the highest one, compare to that, and return the one you end up with.

public static int max(int[] array) {
 if(array.length == 0)
     return; //array should have elements

 int maxt = array[0]; 

 for(int i=1;i < array.length;i++)
 {
     if(array[i] >  maxt)
        maxt = array[i];
 }
 return maxt;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top