在包含 forEach 循环的行上抛出了越界异常,但据我所知,这段代码没有任何问题。 for 循环从 char 数组的元素 0 开始并循环直到到达最后一个元素...但是当我使用更长的 for 循环尝试此代码时,即,
for(int i = 0; i < nested.length; i++)
代码按预期工作。
为什么在这种情况下 for 循环可以工作而 forEach 循环不能工作?
public static void main(String[] args) {
String S = "hello";
String curly1 = "{";
String box1 = "[";
String p1 = "(";
String curly2 = "}";
String box2 = "]";
String p2 = ")";
char[] nested = S.toCharArray();
int flag = 0;
if(nested[0] != curly1.charAt(0)) flag = 0;
if(nested[nested.length-1] != curly2.charAt(0)) flag = 0;
for(char i : nested) {
if(nested[i] == curly1.charAt(0) && nested[(i+1)] == box1.charAt(0) || nested[i] == box1.charAt(0) && nested[(i+1)] == p1.charAt(0)) {
flag = 1; }
else if(nested[i] == p2.charAt(0) && nested[(i+1)] == box2.charAt(0) || nested[i] == box2.charAt(0) && nested[(i+1)] == curly2.charAt(0)) {
flag = 1; }
else { flag = 0;}
}
System.out.println(flag);
}
}
如果您需要在循环中使用索引访问某些内容,请使用 for,而不是 foreach(增强的 for)。
现在您正在访问nested
使用变量的数组i
类型的char
。变量i
代表一个元素nested
正在迭代的数组。因此,如果您使用此变量访问数组,其值将隐式转换为其 int 表示形式(例如'a' == 97
),这将导致异常。
在您的情况下,您需要 for 循环,或者将当前索引值保留在其他变量中并在每次迭代时递增它,因为您无法使用增强的 for 执行此类索引算术:nested[i + 1]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)