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

时间:2017-11-27 18:57:37

标签: 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();
}

}

1 个答案:

答案 0 :(得分:7)

构造函数中不需要var classname = document.getElementsByClassName("classname"); var myFunction = function() { var attribute = this.getAttribute("data-myattribute"); alert(attribute); }; for (var i = 0; i < classname.length; i++) { classname[i].addEventListener('click', myFunction, false); } ,因为构造函数的工作是创建一个对象。 return运算符为您返回该对象,因此它不需要在构造函数本身中。

您的其他方法声明的返回类型为new,这意味着它们不返回任何内容,因此您不需要void语句。

你在一个执行三次的循环中调用return

相关问题