编写一个类,描述学生的学号 姓名 成绩,编写一个测试类,输入学生的学号和成绩,并显示该学号的学生的姓名和成绩,java
时间: 2024-11-18 21:18:15 浏览: 47
在Java中,你可以创建一个简单的`Student`类来存储学生的信息,然后创建一个`TestClass`来操作这个类。首先,我们定义`Student`类:
```java
public class Student {
private int studentId;
private String name;
private double score;
// 构造函数
public Student(int id, String name, double score) {
this.studentId = id;
this.name = name;
this.score = score;
}
// 获取和设置属性的方法
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
```
接下来,我们编写`TestClass`来展示如何根据学号查询并打印学生的姓名和成绩:
```java
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
// 创建一个Student实例列表
Student[] students = new Student[2]; // 示例中有两个学生
// 初始化学生信息
students[0] = new Student(1, "小明", 85);
students[1] = new Student(2, "小红", 92);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学号:");
int inputId = scanner.nextInt();
// 遍历学生数组查找匹配的学号
for (Student student : students) {
if (student.getStudentId() == inputId) {
System.out.printf("学号 %d 的学生姓名是 %s,成绩是 %.2f%n", inputId, student.getName(), student.getScore());
break;
}
}
scanner.close();
}
}
```
当你运行`TestClass`,它会提示用户输入学号,然后根据输入找到对应的学生并打印其姓名和成绩。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](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)