timi先生 2020-05-21 14:34 采纳率: 50%
浏览 130
已采纳

小白求问,有没有大佬看看这个错哪了

public class Solution {

public static void main(String[] args) {
    Person person = new Person();
   System.out.println("年龄:" + age);
    person.adjustAge(age);
    System.out.println("调整后的年龄:" + age);
}

public static class Person {
    public int age = 20;

    public void adjustAge(int age) {
        age = age + 20;

        System.out.println("adjustAge() 中的年龄为 " + age);
    }
}

}
要调用一次adjustAge方法,最后输出年龄是40

  • 写回答

2条回答 默认 最新

  • ZhouSiAn 2020-05-21 14:57
    关注

    首先你main函数里未声明age变量。其次在调用person.adjustAge时传入的变量是在main函数中声明的变量,即实参。最后调用person.adjustAge没有返回参数值。修改后的代码如下,应该符合你的要求。
    public static void main(String[] args) {
    Person person = new Person();
    int age = 20;
    System.out.println("年龄:" + age);
    age = person.adjustAge(age);
    System.out.println("调整后的年龄:" + age);
    System.out.println("调整后person的年龄:" + person.age);
    }

    public class Person {
    public int age = 20;
    
    public int adjustAge(int age) {
        this.age = age + 20;
    
        System.out.println("adjustAge() 中传入的年龄为 " + age);
        return this.age;
    }
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • threenewbee 2020-05-21 14:42
    关注

    问题解决的话,请点采纳

    关键是你的成员变量叫age,参数也叫age,要么用this.age和age区分,要么换名字,换名字比较好

    public class Solution {
    public static void main(String[] args) {
        Person person = new Person();
       System.out.println("年龄:" + person.age);
        person.adjustAge(age);
        System.out.println("调整后的年龄:" + person.age);
    }
    
    public class Person {
        public int age = 20;
    
        public void adjustAge(int _age) {
            age = age + _age;
    
            System.out.println("adjustAge() 中的年龄为 " + age);
        }
    }
    }
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Arduino实现音频混响
  • ¥15 cuda.jit加速报错
  • ¥15 Octave 安装工具箱出错 Only Win32 target is supported!
  • ¥15 docker save的不能在另一台设备运行
  • ¥15 Unity Animation Rigging使用问题
  • ¥15 mbedtls握手返回-7200
  • ¥30 c++ http服务器
  • ¥15 express连接mssql,每条额外附加了语句
  • ¥20 IQOO12如何有效ADB方法
  • ¥15 ios如何获取用户的订阅情况