Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:在for循环init中初始化多个变量?_Java_For Loop - Fatal编程技术网

Java:在for循环init中初始化多个变量?

Java:在for循环init中初始化多个变量?,java,for-loop,Java,For Loop,我想要两个不同类型的循环变量。有什么办法可以让这一切顺利进行吗 @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, cu

我想要两个不同类型的循环变量。有什么办法可以让这一切顺利进行吗

@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();
}
@覆盖
public T get(int index)抛出IndexOutOfBoundsException{
//第一个“int”出现语法错误
对于(节点当前=第一个,int currentIndex;当前!=null;
当前=当前。下一步,currentIndex++){
如果(currentIndex==索引){
返回当前数据;
}
}
抛出新的IndexOutOfBoundsException();
}

只要将变量声明(
节点当前值
int currentIndex
)移到循环之外,它就应该可以工作了。像这样的

int currentIndex;
Node<T> current;
for (current = first; current != null; current = current.next, currentIndex++) {
int-currentIndex;
节点电流;
for(current=first;current!=null;current=current.next,currentIndex++){
甚至可能

int currentIndex;
for (Node<T> current = first; current != null; current = current.next, currentIndex++) {
int-currentIndex;
for(节点当前=第一个;当前!=null;当前=当前。下一个,currentIndex++){

您不能这样做。您可以为(Object var1=null,var2=null;…)使用多个相同类型的变量
或者提取另一个变量并在for循环之前声明它。

语句遵循for的规则

这是合法的(如果愚蠢的话):

这样可以确保不会意外地在方法中的其他位置重用变量

初始化块中声明的变量必须为相同类型

我们不能根据for循环中不同的数据类型的设计来初始化它们。我只是举一个小例子

for(int i=0, b=0, c=0, d=0....;/*condition to be applied */;/*increment or other logic*/){
      //Your Code goes here
}

两者都不会编译:在使用之前必须初始化变量。@unbeli好吧,我没有在手动代码编译中练习:)我只是想给出想法。@unbeli:只是澄清一下:currentIndex需要初始化。Nikita对它做的第一件事是“currentIndex++”,这自然会提出一个问题,increment what?current很好,因为第一个用法是将其设置为first。通常,为了更好地在for循环中编写增量,应该使用++var作为编译器所需的符号var+,以复制var的内容,然后再将其作为表达式alt的结果返回当然,编译器会对此进行优化,但这就像在路上扔垃圾,等待其他人清理一样。
首先是什么?
?它没有在任何地方声明。它是类成员吗?你应该接受下面的一个答案。与C不同,Java没有逗号运算符:,可以进行初始化(但不申报)“Nick Heiner”,请您将下面的答案之一标记为“接受”?有人知道为什么语言设计者实现这个看似不必要的约束吗?@ GLIEVIEWJEFF——这是一个单独的问题。@ JavaXelLod,可能是因为历史原因,因为java是C++模型的…见此帖:
{
  int n = 0;
  for (Object o = new Object();/* expr */;/* expr */) {
    // do something
  }
}
for(int i=0, b=0, c=0, d=0....;/*condition to be applied */;/*increment or other logic*/){
      //Your Code goes here
}