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

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

Is there a way to initialize multiple variables in Java?

问题

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

  1. public class Practice {
  2. private int num0;
  3. private int num1;
  4. private int num2;
  5. private int num3;
  6. public Practice() {
  7. num0 = 0 + 0 + 0 + 0;
  8. num1 = 1 + 1 + 1 + 1;
  9. num2 = 2 + 2 + 2 + 2;
  10. num3 = 3 + 3 + 3 + 3;
  11. }
  12. public static void main(String[] args) {
  13. }
  14. }

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

英文:

For example, if I have the code: 

  1. public class Practice {
  2. private int num0;
  3. private int num1;
  4. private int num2;
  5. private int num3;
  6. public Practice() {
  7. num0 = 0 + 0 + 0 + 0;
  8. num1 = 1 + 1 + 1 + 1;
  9. num2 = 2 + 2 + 2 + 2;
  10. num3 = 3 + 3 + 3 + 3;
  11. }
  12. public static void main(String[] args) {
  13. }
  14. }

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.

  1. int[] num = new int[40];
  2. for(int i=0; i&lt;num.length; i++) {
  3. num[i] = i*4;
  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:

确定