请编写一个学生类,包含学号、姓名、成绩,学生类能够输出所有的信息。 编写一个测试类,创建学生对象,要求给学生的成绩不能超过100分。
时间: 2023-09-03 16:26:13 浏览: 101
### 回答1:
好的,以下是学生类的代码:
```python
class Student:
def __init__(self, id, name, score):
self.id = id
self.name = name
if score > 100:
self.score = 100
else:
self.score = score
def display(self):
print("学号:", self.id)
print("姓名:", self.name)
print("成绩:", self.score)
```
以下是测试类的代码:
```python
class Test:
def __init__(self):
self.student = Student("001", "张三", 90)
def run(self):
self.student.display()
test = Test()
test.run()
```
输出结果为:
```
学号: 001
姓名: 张三
成绩: 90
```
### 回答2:
学生类的设计如下:
```java
public class Student {
private String studentId;
private String name;
private double score;
public Student(String studentId, String name, double score) {
this.studentId = studentId;
this.name = name;
setScore(score);
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String 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) {
if (score <= 100) {
this.score = score;
} else {
System.out.println("成绩超过100分,请重新设置成绩!");
}
}
public void displayInfo() {
System.out.println("学号:" + studentId);
System.out.println("姓名:" + name);
System.out.println("成绩:" + score);
}
}
```
测试类的设计如下:
```java
public class TestStudent {
public static void main(String[] args) {
Student student1 = new Student("001", "张三", 90);
Student student2 = new Student("002", "李四", 110);
student1.displayInfo();
student2.displayInfo();
}
}
```
以上代码中,`Student`类具有学号、姓名和成绩三个属性,其中成绩属性有一个setter方法进行限制,如果成绩超过100分,则输出提示信息。`displayInfo()`方法用于输出学生对象的所有信息。
测试类`TestStudent`中创建了两个学生对象,分别设置了正确和错误的成绩,然后调用`displayInfo()`方法输出学生的所有信息。
### 回答3:
学生类(Student)的代码如下:
```python
class Student:
def __init__(self, student_id, name, score):
self.student_id = student_id
self.name = name
if score > 100:
self.score = 100
else:
self.score = score
def print_info(self):
print("学号:", self.student_id)
print("姓名:", self.name)
print("成绩:", self.score)
```
测试类(Test)的代码如下:
```python
class Test:
def __init__(self):
# 创建学生对象
self.student = Student("2021001", "张三", 95)
def run(self):
# 输出学生信息
self.student.print_info()
# 实例化测试类并运行
test = Test()
test.run()
```
以上代码中,学生类包含了学号、姓名和成绩三个属性。在初始化学生对象时,判断成绩是否超过100分,如果超过则将成绩设为100。学生类还有一个打印信息的方法,用于输出学生的所有信息。
测试类中,创建了一个学生对象,并调用了打印信息的方法,输出学生的所有信息。