统计学生年龄异常的人数。(10分) 定义Student类 (1)成员变量有:姓名,年龄。 (2)对成员变量进行封装。 (3)定义getXXXX,setXXXX方法,其中对年龄的限定条件是:年龄大于0。 定义主类,包含主方法 实现输入5个学生,输出年龄不符合要求 的学生人数和姓名。 如果年龄全部正确,输出“right”,如果全部错误,输出"all wrong"。
时间: 2024-02-28 19:56:53 浏览: 44
好的,根据您的要求,这里是代码实现:
```java
import java.util.Scanner;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Student[] students = new Student[5];
int count = 0;
for (int i = 0; i < students.length; i++) {
System.out.print("请输入第" + (i + 1) + "个学生的姓名和年龄(用空格分隔):");
String name = input.next();
int age = input.nextInt();
students[i] = new Student(name, age);
if (students[i].getAge() <= 0) {
count++;
System.out.println(students[i].getName() + " 的年龄不符合要求!");
}
}
if (count == students.length) {
System.out.println("all wrong");
} else if (count == 0) {
System.out.println("right");
} else {
System.out.println("年龄不符合要求的学生人数为:" + count);
}
}
}
```
代码思路如下:
1. 定义 `Student` 类,并在其中封装姓名和年龄两个成员变量,以及对其的 `get` 和 `set` 方法。
2. 在主类 `Main` 中,通过 `Scanner` 类实现用户输入 5 个学生的姓名和年龄,并将其存储到 `students` 数组中。
3. 在存储过程中,判断学生的年龄是否符合要求,如果不符合,累加计数器 `count`,并输出该学生的姓名和年龄不符合要求的提示信息。
4. 最后,根据 `count` 的值输出相应的结果,如果 `count` 等于 5,即所有学生年龄都不符合要求,则输出 "all wrong";如果 `count` 等于 0,即所有学生年龄都符合要求,则输出 "right";否则输出年龄不符合要求的学生人数,并列出其姓名。
希望这份代码能够满足您的需求,如有疑问或需要进一步帮助,请随时联系我。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)