Initialize multiple variables at the same time after a type has already been defined in Java?

后端 未结 3 561
醉话见心
醉话见心 2021-01-28 10:50

Need a little bit of help with syntax here. I\'m trying to re-initialize multiple variables after the type has already been defined. So for example

int bonus, sa         


        
3条回答
  •  無奈伤痛
    2021-01-28 11:25

    I think you are confused as to be behavior of int bonus, sales, x, y = 50;. It initializes y to 50 and leaves the rest uninitialized.

    To initialize all of them to 50, you have to:

    int bonus = 50, sales = 50, x = 50, y = 50;
    

    You can then change their values:

    bonus = 25;
    x = 38;
    sales = 38;
    
    // or compact
    bonus = 25;   x = 38;   sales = 38;
    
    // or to same value
    bonus = x = sales = 42;
    

    Unlike the C language where you can use the comma syntax anywhere, in Java you can only use that when declaring the variables, or in a for loop: for (i=1, j=2; i < 10; i++, j+=2)

提交回复
热议问题