在Java實際開發中,求余運算(求模運算)通常用于處理整數除法的結果。以下是一些常見的應用場景:
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DateDifference {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2021, 1, 1);
LocalDate date2 = LocalDate.of(2021, 12, 31);
long daysBetween = ChronoUnit.DAYS.between(date1, date2);
long monthsBetween = ChronoUnit.MONTHS.between(date1, date2);
long yearsBetween = ChronoUnit.YEARS.between(date1, date2);
System.out.println("Days between: " + daysBetween);
System.out.println("Months between: " + monthsBetween);
System.out.println("Years between: " + yearsBetween);
}
}
public class LoopIteration {
public static void main(String[] args) {
int divisor = 3;
int dividend = 15;
int loopCount = dividend % divisor;
System.out.println("Loop count: " + loopCount);
}
}
public class ModuloHash {
public static void main(String[] args) {
String input = "Hello, World!";
int modulus = 100;
int hashValue = input.hashCode() % modulus;
System.out.println("Hash value: " + hashValue);
}
}
public class StateMachine {
public static void main(String[] args) {
int currentState = 1;
int totalStates = 5;
int nextState = (currentState - 1 + totalStates) % totalStates;
System.out.println("Next state: " + nextState);
}
}
這些僅僅是Java求余運算在實際開發中的一些應用示例。你可以根據自己的需求靈活運用求余運算來解決各種問題。