在包含forEach循环的行上抛出了一个outofbounds异常,但据我所知,这段代码没有任何问题。 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);
}
}
答案 0 :(得分:0)
如果您需要在循环使用中使用索引来访问某些内容,而不是foreach(enhaced for)。
现在,您正在使用nested
类型的变量i
访问char
数组。变量i
表示正在迭代的nested
数组的元素。因此,如果使用此变量访问数组,则其值将隐式转换为其int表示形式(例如'a' == 97
),这将导致异常。
在你的情况下,你需要for循环,或者将当前索引值保存在其他变量中,并在每次迭代时递增它,因为你不能使用增强的for nested[i + 1]
<进行这种索引算术。 / p>
答案 1 :(得分:0)
foreach循环不会为您提供索引,它会为您提供数组中的元素。因此char i
是数组中的chars
之一。在那之后,你说nested[i]
好像i
是一个索引,但事实并非如此。 chars
具有数值,但数值可能大于数组的长度。此外,使用foreach循环时,在尝试使用nested[(i+1)]
进行迭代时,没有好的方法可以获取元素。坚持使用正常的for
循环。
答案 2 :(得分:0)
因为在每个版本中你都试图通过字符元素访问数组索引。
for(char i:nested) { //这里我是一个字符而不是数组索引所以嵌套[i]没有访问正确的索引。 }
答案 3 :(得分:0)
foreach循环将i中的字符输入到数组中。 你不能用这种循环做你想做的事情,因为你不能预见到下一个角色
for(char i : nested) {
if(i == curly1.charAt(0) && ...
答案 4 :(得分:0)
在foreach for(char i:nested)循环 i 是数组中的元素not 数组索引
你可以先初始化数组索引然后在for循环中递增它;
int index =0;
for(char i : nested) {
index ++;
}
答案 5 :(得分:0)
在第一种情况下(for(int i = 0; i < nested.length; i++)
),变量i
是数组的索引。
在第二种情况下,您使用forEach
迭代构造,它遍历元素,而不是通过索引。
构造for(char i : nested)
具有误导性,因为它使您仍然认为i
是索引,而不是。{1}}。如果你写for(char element : nested)
,那么代码就会清晰,而不是nested[i]
,你应该只使用element
。
但是,使用这种方法,您将无法访问数组中的下一个元素(nested[i+1]
),因此这种迭代不适合您的情况。