描述
采用封装的思想,为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=200; }else{ this.age=age; } } public int getAge(){ return age; } }
验证年龄
最新推荐文章于 2023-06-25 17:39:15 发布
该篇博客介绍了如何使用Java的封装思想来定义Person类的年龄属性,确保年龄值在0到200的范围内。通过设置setter方法进行年龄的校验,当输入的年龄小于0时,年龄设为0;大于200时,设为200。博客提供了代码示例,展示了如何读取用户输入并输出校验后的年龄值。
摘要由CSDN通过智能技术生成