Return a range of int as array - Java java.lang

Java examples for java.lang:int

Description

Return a range of int as array

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        int excludedEnd = 42;
        System.out.println(java.util.Arrays.toString(range(excludedEnd)));
    }//from w  ww .  j  av a 2  s  .com

    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