简体   繁体   English

是什么导致此循环超出范围?

[英]what's causing this loop to go out of bounds?

I'm writing a word find game and can't find why the while loop is giving me ArrayIndexOutOfBounds error. 我在写寻字游戏,找不到为什么while循环给我ArrayIndexOutOfBounds错误。 The error says it is in this line: grid[i-1][j-1]=kb.next(); 错误说它在这行中: grid[i-1][j-1]=kb.next(); but I can't see why? 但我不明白为什么?

代码屏幕截图

(You should have posted your code) but, your while loop is going till: (您应该已经发布了代码),但是,您的while循环将持续到:

while(i<=height) 

and

while(i<=widht)

They should be 他们应该是

while(i < height) and while(i < width) while(i < height)while(i < width)

Since the array index starts with 0 and will continue to Length - 1 , (Also you need to reset j value after coming out of inner loop) 由于数组索引以0开头,并将继续为Length - 1(另外,从内循环出来后还需要重置j值)

It's a simple logic error. 这是一个简单的逻辑错误。 You are not resetting the value of j after you come out of while loop (j <= width). 从while循环退出后,无需重置j的值(j <= width)。 As a result for next value of i the value of j starts from the last possible index value and not from 0. 结果,对于下一个i值,j的值从最后一个可能的索引值开始,而不是从0开始。

Reset j to 1 everytime you come increment value of i after while loop. 每次在while循环后到达i的增量值时,将j重置为1。

Looping over 1 to width (or height) is fine, if not standard practice, since you index with [i-1] or [j-1]. 如果不是标准做法,则可以将1循环到宽度(或高度),因为用[i-1]或[j-1]进行索引。

What your screen capture doesn't show is what the user (you, I assume) entered for "Enter width of grid". 屏幕截图没有显示用户(我想是您)为“输入网格宽度”输入的内容。 Was it the same number for each, or different? 每个数字都相同还是不同? Did you get the first and second indexes switched around? 您是否改变了第一和第二索引?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM