在Java中定义了类型后,同时初始化多个变量?

这里需要一些语法帮助。 我已经尝试在已定义类型后重新初始化多个变量。 所以举个例子

int bonus, sales, x, y = 50; 

这工作正常……但是我想在我的程序中稍后对其中的一些变量添加不同的值,但是我收到了语法错误。

bonus = 25, x = 38, sales = 38;

编译器说我需要

another semicolon for bonus and x

有没有办法在一行代码中更改值? 或者我必须在每个值后面加一个分号?

我认为你很困惑的是int bonus, sales, x, y = 50; 。 它将y初始化为50 ,其余部分未初始化

要将所有这些初始化为50 ,您必须:

 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循环中使用: for (i=1, j=2; i < 10; i++, j+=2)

 int bonus = 25; int x = 38; // or any other value you prefer int sales = 38; 

以后你可以访问变量

 bonus = 35; // and so on... 

方法:你可以这样使用它。

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

在您的代码中,只有y已初始化。

如有任何帮助请访问: http : //wwww.logic4code.blogspot.in/