在Java中定义了类型后,同时初始化多个变量? [英] Initialize multiple variables at the same time after a type has already been defined in Java?
问题描述
这里需要一些语法帮助。我已经尝试在已定义类型后重新初始化多个变量。例如,
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, sales, x, y = 50;
这很好......但是我想稍后在其中一些变量中加入不同的值在我的程序中,但我收到语法错误。
This works fine... however I want to put a different value into some of those variables later on in my program, but I'm getting a syntax error.
bonus = 25,x = 38,sales = 38;
编译器说我需要
奖金和x的另一个分号
。
有没有办法在一行代码中更改值?或者我必须在每个值之后加一个分号?
Is there a way to change the values in a single line of code? Or would I have to put a semicolon after each value??
推荐答案
我认为你很担心是<$的行为c $ c> int bonus,sales,x,y = 50; 。它将 y
初始化为 50
,其余未初始化。
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.
要将所有这些初始化为 50
,您必须:
To initialize all of them to 50
, you have to:
int bonus = 50, sales = 50, x = 50, y = 50;
然后您可以更改其值:
bonus = 25;
x = 38;
sales = 38;
// or compact
bonus = 25; x = 38; sales = 38;
// or to same value
bonus = x = sales = 42;
与您可以使用的 C
语言不同任何地方的逗号语法,在Java中你只能在声明变量时使用它,或者在中用于
循环: for(i = 1,j = 2; i< 10; i ++,j + = 2)
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)
这篇关于在Java中定义了类型后,同时初始化多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!