Java:初始化循环init中的多个变量? [英] Java: Initialize multiple variables in for loop init?

查看:98
本文介绍了Java:初始化循环init中的多个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有两个不同类型的循环变量。有什么办法可以做到这一点吗?



$ @ $ public $ get(int index)throws IndexOutOfBoundsException {
//第一个'int'的语法错误
for(Node< T> current> first,int currentIndex; current!= null;
current = current.next,currentIndex ++){
if(currentIndex == index){
return current.datum;


throw new IndexOutOfBoundsException();


解决方案

初始化 code> 声明遵循局部变量声明



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

< (int a = 0,b [] = {1},c [] [] = {{1},{2}}; a< 10; a ++){pre
//东西
}

但是试图声明不同的<$ c










$ b $

  {
int}可以通过使用如下代码块来限制方法内其他变量的作用域: n = 0;
for(Object o = new Object(); / * expr * /; / * expr * /){
//做某事
}
}

这可以确保您不会在方法的其他地方重复使用变量。

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();
}

解决方案

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.

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.

这篇关于Java:初始化循环init中的多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆