对于以后的程序,我需要创建一个有界整数类,表示0-59(可用于时间问题)。

我无法使其“环绕”。例如,如果我添加int = 54,则边界10应该为4

最佳答案

您可以使用modulo %运算符

int modulo = 60;
int value = 24;
value = (value + 40) % modulo;
System.out.println(value);        //  4
value = (value + 50000) % modulo;
System.out.println(value);        // 34




如果您需要上课,可以执行以下操作:

class MyIntegerBounded {
    private int value;
    private int bound;

    public MyIntegerBounded(int value, int bound) {
        this.value = value;
        this.bound = bound;
    }

    int get() {
        return value;
    }

    void increment() {
        add(1);
    }

    void add(int toAdd) {
        value = (value + toAdd) % bound;
    }
}


使用方法:

public static void main(String[] args) throws InterruptedException {
    MyIntegerBounded m = new MyIntegerBounded(24, 60);
    System.out.println(m.get());   // 24
    m.increment();
    System.out.println(m.get());   // 25
    m.add(40);
    System.out.println(m.get());   //  5
}

关于java - 如何制作有界整数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50592310/

10-11 14:36
查看更多