为什么在这种情况下不需要返回?

Rya*_*yan 0 java

我是编程的新手,我想问为什么在我的代码中我不需要在构造函数和方法中使用return函数?

另外为什么在使用yearPasses函数之后,年龄增加3而不是1?

为漫长的代码道歉

public class Person
{
    private int age;

    public Person(int initialAge)
    {
        // Add some more code to run some checks on initialAge
        if (initialAge<0)
        {
            System.out.println("Age is not valid, setting age to 0.");
            initialAge = 0;
            age = initialAge;
        }
        else
        {
            age = initialAge;
        }
    }

    public void amIOld()
    {
        if (age<13)
        {
            System.out.println("You are young.");
        }
        else if (age>=13 && age<18)
        {
            System.out.println("You are a teenager.");
        }
        else
        {
            System.out.println("You are old.");
        }
    }

    public void yearPasses()
    {
        age = age + 1;
    }

    public static void main(String[] args)
    {
    Scanner sc = new Scanner(System.in);
    int T = sc.nextInt();
    for (int i = 0; i < T; i++)
    {
        int age = sc.nextInt();
        Person p = new Person(age);
        p.amIOld();
        for (int j = 0; j < 3; j++)
        {
            p.yearPasses();
        }
        p.amIOld();
        System.out.println();
    }
    sc.close();
}
Run Code Online (Sandbox Code Playgroud)

}

Bil*_*ard 7

return在构造函数中不需要a ,因为构造函数的工作是创建一个对象.该new操作符返回对象给你,所以它并不需要在构造函数本身.

您的其他方法使用返回类型声明void,这意味着它们不返回任何内容,因此您也不需要return语句.

你正在调用yearPasses一个执行三次的循环.