2015-10-14 86 views
-2

如果我想要一个方法在每次调用方法时都重复返回三个不同的值(不将这些值作为参数传递),有可能吗? 例如 第一次调用方法返回3 第二次调用返回6 第三次调用返回5 然后重复此模式。我们如何实现这一点?在java中,我们可以在每次调用时返回不同的值吗?

+2

是,假设方法获得某种可保持时代的方法被调用次数的跟踪的实例字段 – MadProgrammer

+0

非常感谢你 – iamlearning

回答

-1

更好,如果你使用一个静态字段这个任务做不同的事情: 例如,你的类中:

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; 
} 
-1

你的问题有点不清楚......但也许这可能会根据你的问题工作?这只是下面的例子:

public int ex; 
public int test(){ 
    if(ex == 1){ 
     return 1; 
    } 
    if(ex == 2){ 
     return 2; 
    } 
    // and so on 
} 

然后当你调用它,你可以更改前的东西,这样做:EX =(值);

除此之外,没有其他办法让它每次调用时,我知道

相关问题