#Index an Array out of Bounds

18 messages · Page 1 of 1 (latest)

manic trench
#

Creating a code for class, but having error

grim widgetBOT
#

This post has been reserved for your question.

Hey @manic trench! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

manic trench
#
class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int[] answer = new int[temperatures.length];
        int num = 1;
        int days = 0;

        for(int i=0;i<temperatures.length;i++){
            if(i == temperatures.length - 1)

        answer[i] = 0;

        for(days = i+1; days<temperatures.length; days++)
        num = 1;
            if(temperatures[days] > temperatures[i])
          answer[i] = num;
          num++;
        }
        return answer;
    }
}
#

This is my code and this is the line giving error:

#
if(temperatures[days] > temperatures[i])
#

I don't understand why it's creating error or how to fix it

grim widgetBOT
#

<@&765578700724371486>

Requested by mina?#0001
remote crane
#

you're missing {} on your inner for so it just applies to num = 1;
days = i + 1 is not checked and thus you try to get an index that's out of bounds

#

this is why you scope your variables properly. don't declare days so high in scope that you don't get warnings for bugs you made

#

declare days like you declared i

manic trench
#

i did that originally but it created an error

remote crane
#

yes, as it should

#

so you can get compiler errors instead of runtime errors

#

much easier to trace

manic trench
#

Thank you! That did fix my error, the code isn't correct yet but now I know how to fix the rest sunglassessmug

#

I'll close this now!