문제

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;
}
도움이 되었습니까?

해결책

This is short for:

minutes = minutes % 60;

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

다른 팁

+= 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);

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top