S Dex S Dex - 1 month ago 8
Java Question

Print specific string sequence

this is my first question here.

I need to do a function that returns a specific string sequence, example:

1st call returns "a"
2nd call returns "b",
3rd call returns "c"
4th call returns "a"
5th call returns "a"
6th call returns "b"
7th call returns "b"
8th call returns "c"
9th call returns "c" etc (sequence is a,b,c - a,a,b,b,c,c - a,a,a,b,b,b,c,c,c etc)

The function must return only the specific string, so if i call the function 2 times by doing "println(magicFunction());" twice, it has to return "a" on the fist call and "b" on the second one.

Here is what i tried to do in Java.

public class Main {

static int repetitions = 1;
static int said = 0;
static int cursor = 0;
static String[] list= {"a", "b", "c"};

public static void main(String[] args) {
for (int i = 0; i < 15; i++)
System.out.println(nextStr());
}

public static String nextStr() {

if (said >= repetitions ) {
cursor++;
said = 0;
} else {
said ++;
}

if (cursor == 2 && said == repetitions ) {
cursor = 0;
}

return list[cursor];
}
}

Answer

I think this will achieve what you're after.

cursor starts at 0 and increments by 1 iff queried == queryLetter.

When queried == queryLetter, queried is reset to 0.

If cursor == characters.length then increment queryLetter by 1.

public class Example {

    private static int cursor = 0;
    private static int queryLetter = 1;
    private static int queried = 0;

    public static void main(String[] args) {
        for (int i=0; i<40; i++) {
            System.out.println(magicFunction());
        }
    }

    public static char magicFunction() {
        char[] characters = new char[]{'a', 'b', 'c'};
        char result = characters[cursor];
        if (++queried == queryLetter) {
            if (++cursor == characters.length) {
                cursor = 0;
                queryLetter++;
            }
            queried = 0;
        }
        return result;
    }

}