Domanda

How does %= work in Java? I've been told that it can be used to reassign a value?

Grateful if anyone could teach! Thanks!

minutes=0;
while(true){
minutes++;
minutes%=60;
}
È stato utile?

Soluzione

This is short for:

minutes = minutes % 60;

There are other, similar compound assignment operators for all the binary operators in Java: +=, -=, *=, ^=, ||=, etc.

Altri suggerimenti

+= is add to:

i+=2;

is i = i + 2;

% is remainder: 126 % 10 is 6.

Extending this logic, %= is set to remainder:

minutes%=60;

sets minutes to minutes % 60, which is the remainder when minutes is divided by 60. This is to keep minutes from overflowing past 59.

It's a Modulo operation which is the same as taking the remainder from division. minutes%=60; is the same as minutes = minutes % 60; which is the same as minutes = minutes - (((int) (minutes/60)) * 60);

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top