有没有一种方法可以在Java中初始化多个变量?

huangapple go评论126阅读模式
英文:

Is there a way to initialize multiple variables in Java?

问题

例如,如果我有以下代码:

public class Practice {
    
    private int num0;
    private int num1;
    private int num2;
    private int num3;
    
    public Practice() {
        num0 = 0 + 0 + 0 + 0;
        num1 = 1 + 1 + 1 + 1;
        num2 = 2 + 2 + 2 + 2;
        num3 = 3 + 3 + 3 + 3;
    }
    public static void main(String[] args) {
    }
}

是否有办法使用循环或其他方式使初始化过程变得更简洁?比如说如果我有40个num,是否需要把这整个过程都重复一遍?

英文:

For example, if I have the code: 

public class Practice {
    
    private int num0;
    private int num1;
    private int num2;
    private int num3;
    
    public Practice() {
        num0 = 0 + 0 + 0 + 0;
        num1 = 1 + 1 + 1 + 1;
        num2 = 2 + 2 + 2 + 2;
        num3 = 3 + 3 + 3 + 3;
    }
    public static void main(String[] args) {
    }
}

Is there any way to use a loop or some other way to make the initialization less lengthy? Like if I had 40 nums, would I need to type this whole thing out? 

答案1

得分: 7

int[] num = new int[40];

for(int i=0; i<num.length; i++) {
num[i] = i*4;
}

英文:

That is precisely the use-case of arrays.

int[] num = new int[40];

for(int i=0; i&lt;num.length; i++) {
  num[i] = i*4;
}

huangapple
  • 本文由 发表于 2020年8月27日 03:58:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63604928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定