Fllappy
Fllappy

Reputation: 401

Get consecutive values based on value being passed in

I am looking for a way to pass in a value and get 3 values out of it. Meaning if I pass in the value 0, the print out will be 0 1 2. Thus this is actual value passed in plus the next 2 consecutive numbers.

But it's not just the about consecutive numbers. For example, if I pass in 1, I am NOT expecting 1 2 3. Instead it should be as follows.

The following code works as intended but kinda silly to be writing it out this way plus the value being passed in is determined by external factors and I won't know it beforehand.

But if the value passed in is example 3, the algorithm should calculate that

3 multiples of 3 has passed (index 0 - 8).

Thus passing in 3 would mean print 9, 10, 11.

The following code does whats explained above. But is not scalable thus looking for some sort of looping algorithm.

class App {

    public static void main(String[] args) {

        App app = new App();
        app.printIndex(0); // idea is to print the index being passed in and the next 2 numbers, so 0 1 2
        app.printIndex(1); // 3 4 5
        app.printIndex(2); // 6 7 8
        app.printIndex(3); // 9 10 11
    }

    int getIndex(int i) {
        if(i == 0) return i;

        if(i == 1) return 3;

        if(i == 2) return 6;

        if(i == 3) return 9;

        return 0;
    }

    void printIndex(int i) {

        System.out.println(getIndex(i));
        System.out.println(getIndex(i) + 1);
        System.out.println(getIndex(i) + 2);
    }
}

Upvotes: 1

Views: 69

Answers (1)

Luke
Luke

Reputation: 154

int getIndex(int i) {
    return i*3;
}

your getIndex method needs to just return i*3 to get every 3rd number. Your program should work if you just replace this. You could even leave out the getIndex() method entirely if you edit your printIndex() method to

void printIndex(int i) {
    System.out.println(i*3+"");
    System.out.println(i*3 + 1);
    System.out.println(i*3 + 2);
}

Upvotes: 1

Related Questions