每次超过一定数量时如何返回未更改的变量?

时间:2018-06-03 18:34:55

标签: java methods int

我试图让变量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);} 
  }

2 个答案:

答案 0 :(得分:1)

x是一个局部变量。如果您希望它在调用之间保留其值,则必须将其保存在数据成员中(在本例中为静态成员,因为method是静态的):

private static int x = 0;
static int method(int r) {
    int temp = x + r;
    if (temp < 10) {
        x = temp;
    }
    return x;
}

答案 1 :(得分:0)

你的方法改变了这个问题:

public class test1 {

    static int x = 0;
    static int method(int r) {

        int t = x + r;
        if (t < 10) {
            x = t;
        }
        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);} 
      }

输出:

4
4
9