编写一个满足下列要求的程序: 定义学生类,属性分别是:姓名(name,String)、学号(ID,int)和年级(state,int,1:新生,2:二年级,3:三年级,4:四年级)。 创建30个学生,学生的姓名、学号、年级通过键盘输入。 查找二年级的学生人数,并输出姓名和学号。
时间: 2023-05-10 10:55:35 浏览: 135
以下是满足要求的程序:
```java
import java.util.Scanner;
public class Student {
private String name;
private int ID;
private int state;
public Student(String name, int ID, int state) {
this.name = name;
this.ID = ID;
this.state = state;
}
public String getName() {
return name;
}
public int getID() {
return ID;
}
public int getState() {
return state;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Student[] students = new Student[30];
for (int i = 0; i < students.length; i++) {
System.out.print("请输入第" + (i + 1) + "个学生的姓名:");
String name = scanner.next();
System.out.print("请输入第" + (i + 1) + "个学生的学号:");
int ID = scanner.nextInt();
System.out.print("请输入第" + (i + 1) + "个学生的年级(1:新生,2:二年级,3:三年级,4:四年级):");
int state = scanner.nextInt();
students[i] = new Student(name, ID, state);
}
int count = 0;
System.out.println("二年级的学生有:");
for (Student student : students) {
if (student.getState() == 2) {
count++;
System.out.println("姓名:" + student.getName() + ",学号:" + student.getID());
}
}
System.out.println("共" + count + "人");
}
}
```
如果您有更好的实现方式,欢迎分享!
阅读全文