简体   繁体   English

Java:生成一定范围内的数字序列?

[英]Java: Generate a sequence of numbers within a range?

I need to be able to generate a series of ascending or descending numbers within a range. 我需要能够生成一个范围内的一系列上升或下降数字。

public int nextInRange(int last, int min, int max, int delta, boolean descending) {
        delta *= descending ? -1 : 1;

        int result = last + delta;
        result %= max;
        return Math.max(result, min);
}

This works fine for ascending values, but not descending values. 对于升序值,但对于降序值,此方法效果很好。 I've been staring at this for a while, and I'm not sure how to make it work for descending values. 我已经盯着看了一段时间了,我不确定如何使它适用于下降值。 Any ideas? 有任何想法吗?

How about this, where delta is negative when you want a descending sequence? 怎么样,当您想要一个降序序列时, delta为负?

public int nextInRange(int last, int min, int max, int delta) {
    int result = last + delta;

    // now clip to min and max
    if (result > max) {
        result = max;
    } else if (result < min) {
        result = min;
    }

    return result;
}

or perhaps less straightforwardly, have the body of the function be the single line: 或可能不太直接,使函数的主体为单行:

return Math.min(max, Math.max(last + delta, min));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM