我想要两个不同类型的循环变量.有没有办法让这项工作?
@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();
}
Run Code Online (Sandbox Code Playgroud)
McD*_*ell 98
这是合法的(如果愚蠢):
for (int a = 0, b[] = { 1 }, c[][] = { { 1 }, { 2 } }; a < 10; a++) {
// something
}
Run Code Online (Sandbox Code Playgroud)
但是尝试根据需要声明distinct Node
和int
类型对于局部变量声明来说是不合法的.
您可以使用如下块来限制方法中的其他变量的范围:
{
int n = 0;
for (Object o = new Object();/* expr */;/* expr */) {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
这可确保您不会意外地在方法中的其他位置重用该变量.
只需在循环外部移动变量声明(Node<T> current
,int currentIndex
)即可.像这样的东西
int currentIndex;
Node<T> current;
for (current = first; current != null; current = current.next, currentIndex++) {
Run Code Online (Sandbox Code Playgroud)
或者甚至是
int currentIndex;
for (Node<T> current = first; current != null; current = current.next, currentIndex++) {
Run Code Online (Sandbox Code Playgroud)
在初始化块中声明的变量必须是相同的类型
我们不能按照他们的设计在 for 循环中初始化不同的数据类型。我只是举一个小例子。
for(int i=0, b=0, c=0, d=0....;/*condition to be applied */;/*increment or other logic*/){
//Your Code goes here
}
Run Code Online (Sandbox Code Playgroud)