Doesn’t Index work on Arrays?

Asked

Viewed 249 times

0

I have the following code that holds an array of 7 values, each for each day of the week. then I have to create a function that sums these 7 values (successfully concluded), tells what is the highest value of this Array (successfully completed) and then indicates which day the value occurred (where the proleme is). I still have a problem with int day=rainHours.indexof(maxTempDay); where it says "cannot find Symbol - method indexof(int). I leave here the code would appreciate help.

public static void main(String[] args)
{
    int [] rainHours=new int[]{1,3,0,0,6,3,8};
    int sum = rainInBusyDays(rainHours);
    System.out.println(sum);
    int maxValue=maxRain(rainHours);
    int maxTempDay=mostRainy(rainHours);
    int day=rainHours.indexOf(maxTempDay);
    System . out . println("O valor máximo é:" + maxValue + " no " + day + "º dia da semana ");

}

public static int rainInBusyDays(int[] rainH)
{
    int total = 0;
    for (int i =1; i<rainH.length-1 ;i++)
    {
        total =total + rainH[i];
    }
    return total;
}

public static int maxRain(int[] rainHo)
{
    int max = 0;
    for(int j=0;j<rainHo.length;j++)
    {
        if (rainHo[j] > max)
        {
            max= rainHo[j];
        }
    }
    return max;
}

public static int mostRainy(int[] rainHou)
{
    int maxTempDay = 0;
    for(int k = 0 ; k<rainHou.length;k++)
    {
        if(rainHou[k] > maxTempDay)
        {
            maxTempDay = rainHou[k];             
        }
    }
    return maxTempDay;
}

1 answer

3


There is no method indexOf for arrays. If you want to know the int index in the array you can:

1 - Make a for in the array looking for the element (This function returns the day it had the maximum temperature, if it does not find this temperature it returns -1)

public int maxTempDay(int maxTemp, int[] days) {
    for(int i = 0 ; i< days.length; i++) {
        if(maxTemp == days[i]) {
            //retorna o dia em que a temperatura estava máxima. 
            //Como o índice do array começa do zero você pode retornar i+1 para ter o dia;
            return i+1;
        }
    }
    // se terminar o for, não foi encontrado um dia com essa temperatura.
    return -1;
}

2 - Use the class java.util.Arrays to use the method indexOf of a List

java.util.Arrays.asList(rainHours).indexOf(maxTempDay);
  • So how do I call this "i" so you can give Return on the correct day to print on the main function?

  • @Phil I edited my answer explaining to you how to use the i

Browser other questions tagged

You are not signed in. Login or sign up in order to post.