为什么++不向整数值添加一个

时间:2016-06-17 09:28:59

标签: java android

我的代码中有以下几行:

   Log.d ("Playlist", "Current Song Number is: "+ currentSongNumber );

   currentSongNumber = currentSongNumber++;

   Log.d ("Playlist", "Current Song Number has changed to: "+ currentSongNumber );

但我得到了结果:

Current Song Number is: 2
Current Song Number has changed to: 2

那么为什么它没有变成三个只有++才能在迭代时起作用?

5 个答案:

答案 0 :(得分:4)

后增量运算符返回值,然后递增。通过分配回相同的变量,您可以放弃对变量执行的增量。

所以当你这样做时

currentSongNumber = currentSongNumber++;

它等同于以下代码:

int oldValueOfCurrentSongNumber = currentSongNumber;
currentSongNumber = currentSongNumber + 1;
currentSongNumber = oldValueOfCurrentSongNumber;  // This is because of your assignment

答案 1 :(得分:1)

试试这段代码: currentSongNumber ++;

答案 2 :(得分:1)

因为您正在使用后期增量

所以要么试试这个

currentSongNumber = ++currentSongNumber;

或者

currentSongNumber++;

或者

++currentSongNumber;

答案 3 :(得分:1)

您正在使用帖子增量。点击here查看预增量和后增量之间的差异。在你的代码中尝试预增量。

++currentSongNumber;

这将为您提供所需的输出。

在您的代码中,如果您使用currentSongNumber = currentSongNumber++;而不是currentSongNumber,则会将currentSongNumber = currentSongNumber+1;的值分配给自己,这与之前相同,而且会增加。

或者您可以只使用public class MyObject: RealmObject { public int IdColor {get; set;} public Color color { get { return realm.All<Color>().FirstOrDefault(x => x.Id == IdColor); } set { IdColor = value.Id; } } } ,以避免混淆。

答案 4 :(得分:1)

在家里试试这个:

Log.d ("Playlist", "Current Song Number is: "+ currentSongNumber );

  currentSongNumber++;

   Log.d ("Playlist", "Current Song Number has changed to: "+ currentSongNumber );