0

Why this while loop give me an exception e?

I have: int c=input[0]; //input is a int string with 4 elements while(sum<input.lenght) { sum+=2; c+=input[sum]; }

29th Oct 2017, 3:51 AM
López Rodrigo
López Rodrigo - avatar
6 ответов
+ 5
In you while loops comparison you have sum < input.length where the length of the input array is 4, the last elements index would be 3. This means that any integer value greater than 3 would attempt to access a location in memory that is beyond the end of the array, or outside of the array. This comparison would be fine normally, but you are incrementing the sum as the index within the array itself after this check is taking place and before you use the sum variable as the arrays index. Subtracting 2 from the input.length will ensure that when the sums value is greater than 2 that this error won't happen. If the value of sum was initially 0 before the while loop then 0 < 4 would be true and the loop will be entered. Then you run sum+=2 which makes sums value equal to 2. This value is used to access the value at the index of 2 from the input array. Next, the comparison check for the while loop is done again, 2 < 4, which is true. The body of the loop is once again entered and the value of sum is increased to 4. Now, when the value of 4 is used to attempt to access the input array, you are going beyond the end of the array, as its last index is 3. This results in the error.
29th Oct 2017, 5:46 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
No, but you can copy and paste it into the code playground, or upload it somewhere else and post a link. There are also other online IDE's, such as the ones at tutorialspoint.com that you can use. Some will allow you to import a project from a source such as github, Dropbox etc, and let you share a permalink or embed the code.
29th Oct 2017, 6:00 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Other than the fact you spelled length wrong, there isn't enough information in this code to tell you if there are any other errors here. That and adding 2 to sum within the while loop, while using it as the index is asking for an array index out of bounds exception. Subtract 2 from input.length to fix this issue. If that isn't the issue then you need to include more of the code or link to it
29th Oct 2017, 4:16 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
Thanks!! Now I understand.
29th Oct 2017, 5:41 AM
López Rodrigo
López Rodrigo - avatar
+ 1
Substracting 2 from input.lenght was enough, than you!! But I don't understand why is origined the exception. I think that when sum==input.length the while is not executed and the program steps to the next code line.
29th Oct 2017, 5:30 AM
López Rodrigo
López Rodrigo - avatar
0
Thanks!!! I have another question. Is it possible to upload a code file? (written out of the codeplayground)
29th Oct 2017, 5:51 AM
López Rodrigo
López Rodrigo - avatar