递归求年龄

题目:有5 个人坐在一起,问第五个人多少岁?他说比第 4 个人大 2 岁。问第 4 个人岁数,他说比第 3 个人大 2 岁。问第三个人,又说比第 2 人大两岁。问第 2 个人,说比第一个人大两岁。最后问第一个人,他说是 10 岁。请问第五个人多大?

 

建立一个People类:

 

package com.edu.jmu.classical;

public class People {

	private int id;
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public People(int id, int age) {
		this.id = id;
		this.age = age;
	}

	public People(int id) {
		this.id = id;
	}

	public int older(People people) {
		if (people.getId() == 1) {
			return 10;
		} else {
			int id = people.getId() - 1;
			return 2 + this.older(new People(id));
		}
	}

}

 

再建立一个测试类TestPeople:

 

package com.edu.jmu.classical;

public class TestPeople {
	public static void main(String[] args) {
		People people = new People(5);
		System.out.println(people.older(people));
	}
}

 

结果输出:

 

18

你可能感兴趣的:(递归)