英文:
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<num.length; i++) {
num[i] = i*4;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论