Java:在for循环init中初始化多个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3542871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Initialize multiple variables in for loop init?
提问by Nick Heiner
I want to have two loop variables of different types. Is there any way to make this work?
我想要两个不同类型的循环变量。有什么办法可以使这项工作?
@Override
public T get(int index) throws IndexOutOfBoundsException {
// syntax error on first 'int'
for (Node<T> current = first, int currentIndex; current != null;
current = current.next, currentIndex++) {
if (currentIndex == index) {
return current.datum;
}
}
throw new IndexOutOfBoundsException();
}
回答by Nikita Rybak
Just move variable declarations (Node<T> current
, int currentIndex
) outside the loop and it should work. Something like this
只需将变量声明 ( Node<T> current
, int currentIndex
)移到循环之外,它应该可以工作。像这样的东西
int currentIndex;
Node<T> current;
for (current = first; current != null; current = current.next, currentIndex++) {
or maybe even
或者甚至
int currentIndex;
for (Node<T> current = first; current != null; current = current.next, currentIndex++) {
回答by Colin Hebert
You can't like this. Either you use multiple variables of the same type for(Object var1 = null, var2 = null; ...)
or you extract the other variable and declare it before the for loop.
你不能喜欢这个。要么使用多个相同类型的变量,要么for(Object var1 = null, var2 = null; ...)
提取另一个变量并在 for 循环之前声明它。
回答by McDowell
The initialization of a for
statement follows the rules for local variable declarations.
This would be legal (if silly):
这将是合法的(如果愚蠢的话):
for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {
// something
}
But trying to declare the distinct Node
and int
types as you want is not legal for local variable declarations.
但是尝试根据需要声明不同的Node
和int
类型对于局部变量声明是不合法的。
You can limit the scope of additional variables within methods by using a block like this:
您可以使用这样的块来限制方法中附加变量的范围:
{
int n = 0;
for (Object o = new Object();/* expr */;/* expr */) {
// do something
}
}
This ensures that you don't accidentally reuse the variable elsewhere in the method.
这可确保您不会意外地在方法的其他地方重用该变量。
回答by Vishnu Prasanth G
Variables declared in the initialization block must be of same type
在初始化块中声明的变量必须是相同的类型
we can't initialize the different data types in the for loop as per their design. I'm just putting a small example.
我们不能按照他们的设计在 for 循环中初始化不同的数据类型。我只是举一个小例子。
for(int i=0, b=0, c=0, d=0....;/*condition to be applied */;/*increment or other logic*/){
//Your Code goes here
}