Generate range of integers - Java java.lang

Java examples for java.lang:int

Description

Generate range of integers

Demo Code


//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        int excludedEnd = 42;
        System.out.println(java.util.Arrays.toString(range(excludedEnd)));
    }/*from   www. jav a 2s . co m*/

    public static int[] range(int excludedEnd) {
        return range(0, excludedEnd, 1);
    }

    public static int[] range(int includedStart, int excludedEnd) {
        return range(includedStart, excludedEnd, 1);
    }

    public static int[] range(int includedStart, int excludedEnd, int step) {
        if (includedStart > excludedEnd) {
            int tmp = includedStart;
            includedStart = excludedEnd;
            excludedEnd = tmp;
        }

        if (step <= 0) {
            step = 1;
        }

        int deviation = excludedEnd - includedStart;
        int length = deviation / step;
        if (deviation % step != 0) {
            length += 1;
        }
        int[] range = new int[length];
        for (int i = 0; i < length; i++) {
            range[i] = includedStart;
            includedStart += step;
        }
        return range;
    }
}

Related Tutorials