我试图让变量 x 在加法后返回其值(当其低于 10 时),并且我希望它在每次达到数字 > 10 时返回其未更改的值。我做错了什么?
不成功的代码:
public class test {
static int method(int r){
int x = 0;
x = x + r;
if (x <=10) {
if (x >=10)
return x;} //unsure about this part of the Code.
return x;
}
public static void main(String[] arg) {
int i = method(4);
System.out.println(i); //want it to output 4
i = method(7);
System.out.println(i); //want it to output 4 because 4+7= 12. 12 >10
i = method(5); //want it to output 9
System.out.println(i);}
}
最佳答案
x
是一个局部变量。如果您希望它在调用之间保留其值,则必须将其保存在数据成员中(在本例中为静态成员,因为 method
是静态的):
private static int x = 0;
static int method(int r) {
int temp = x + r;
if (temp < 10) {
x = temp;
}
return x;
}
关于java - 每次超过一定数量时如何返回未更改的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50669704/