#Index an Array out of Bounds
18 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @manic trench! Please use
/closeor theClose Postbutton 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.
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
<@&765578700724371486>
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
i did that originally but it created an error
yes, as it should
so you can get compiler errors instead of runtime errors
much easier to trace
