Search code examples
javareturncall

In java can we return different values with every call?


If I want a method to return three different values repeatedly each time the method is called (without passing those values as a parameter), is it possible? For example 1st call to method returns 3 2nd call returns 6 3rd call returns 5 and then this pattern repeats.How could we achieve that?


Solution

  • better if you use an static field for this task: for example, inside your class:

    private static int myindex=0; //should start at 0
    private static int[] myres={3,6,5};
    public int method(){ //also static?
        int res = myres[myindex];
        myindex++;
        if(myindex>=myres.length)myindex=0; 
        return res;
    }