描述
采用封装的思想,为Person类定义年龄属性,要求:
修改年龄时判断其范围,若年龄小于0则按0输出,若年龄大于200则按200输出。
输入描述:
年龄整数值
输出描述:
1. 若年龄小于0则输出0;
2. 若年龄大于200则输出200;
3. 若年龄介于[0,200]之间则直接输出。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Person p = new Person();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int age = scanner.nextInt();
p.setAge(age);
System.out.println(p.getAge());
}
}
}
class Person {
private int age;
//write your code here......
public void setAge(int age){
if(age<0){
this.age=0;
}else if(age<200){
this.age=age;
}else{
this.age=200;
}
}
public int getAge(){
return age;
}
}