在 java 中,我们可以 return 每次调用都使用不同的值吗?
In java can we return different values with every call?
如果我想要一个方法在每次调用该方法时重复 return 三个不同的值(不将这些值作为参数传递),这可能吗?
例如
第一次调用方法 returns 3
第二次调用 returns 6
第三次通话 returns 5
然后这个模式 repeats.How 我们能实现吗?
您的问题有点不清楚……但根据您的问题,这也许可行?这只是下面的一个例子:
public int ex;
public int test(){
if(ex == 1){
return 1;
}
if(ex == 2){
return 2;
}
// and so on
}
然后当你调用它时,你可以将 ex 更改为某些东西,方法是:ex = (value);
据我所知,除此之外,没有其他方法可以让它在每次调用时做不同的事情
如果您为此任务使用静态字段会更好:
例如,在你的 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;
}
如果我想要一个方法在每次调用该方法时重复 return 三个不同的值(不将这些值作为参数传递),这可能吗? 例如 第一次调用方法 returns 3 第二次调用 returns 6 第三次通话 returns 5 然后这个模式 repeats.How 我们能实现吗?
您的问题有点不清楚……但根据您的问题,这也许可行?这只是下面的一个例子:
public int ex;
public int test(){
if(ex == 1){
return 1;
}
if(ex == 2){
return 2;
}
// and so on
}
然后当你调用它时,你可以将 ex 更改为某些东西,方法是:ex = (value);
据我所知,除此之外,没有其他方法可以让它在每次调用时做不同的事情
如果您为此任务使用静态字段会更好: 例如,在你的 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;
}