用java编写一个有课程名、课程教师、课程教师、课程人数、自己学号、自己性别 赋值给变量,并输出
时间: 2024-09-12 21:11:29 浏览: 80
当然可以。在Java中,你可以创建一个名为`StudentCourse`的对象来存储这些信息,然后通过对象属性进行赋值并输出。下面是一个简单的示例:
```java
public class StudentCourse {
private String courseName;
private String teacher;
private int classSize;
private String studentID;
private String gender;
// 构造函数用于初始化对象
public StudentCourse(String courseName, String teacher, int classSize, String studentID, String gender) {
this.courseName = courseName;
this.teacher = teacher;
this.classSize = classSize;
this.studentID = studentID;
this.gender = gender;
}
// 定义getter和setter方法
public String getCourseName() { return courseName; }
public void setCourseName(String courseName) { this.courseName = courseName; }
public String getTeacher() { return teacher; }
public void setTeacher(String teacher) { this.teacher = teacher; }
public int getClassSize() { return classSize; }
public void setClassSize(int classSize) { this.classSize = classSize; }
public String getStudentID() { return studentID; }
public void setStudentID(String studentID) { this.studentID = studentID; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
// 输出方法
@Override
public String toString() {
return "学生课程信息:\n"
+ "课程名称: " + courseName + "\n"
+ "教师: " + teacher + "\n"
+ "班级人数: " + classSize + "\n"
+ "学号: " + studentID + "\n"
+ "性别: " + gender;
}
}
// 主程序中使用
public static void main(String[] args) {
StudentCourse myCourse = new StudentCourse("计算机科学基础", "张老师", 50, "001", "男");
System.out.println(myCourse);
}
```
在这个例子中,我们首先定义了一个`StudentCourse`类,包含了所需的所有字段以及相关的操作方法。然后,在`main`函数中创建了一个该类的对象,并将其相关信息设置好,最后调用`toString`方法输出整个对象的信息。
阅读全文