编写一个Java程序,为Student类增加一个方法,该方法能够接收参数并对Student类中的各个属性进行赋值,输出学生的姓名、年龄、语文、数学、英语、总成绩和平均成绩。
时间: 2024-06-10 10:03:48 浏览: 11
好的,我可以为您提供一段代码作为参考,实现您所描述的功能。
首先,我们需要在Student类中新增一个方法,例如:
```
public void setScores(String name, int age, float chinese, float math, float english) {
this.name = name;
this.age = age;
this.chinese = chinese;
this.math = math;
this.english = english;
this.totalScore = chinese + math + english;
this.averageScore = this.totalScore / 3;
}
```
这个方法接受五个参数,分别是学生姓名、年龄、语文成绩、数学成绩和英语成绩,它们会被赋值给对应的属性。同时,这个方法会计算学生的总成绩和平均成绩。
接下来,我们可以在主函数中创建一个Student对象,调用这个新增的方法来为其赋值,并输出结果。示例代码如下:
```
public static void main(String[] args) {
Student student = new Student();
student.setScores("张三", 18, 89.5f, 93.0f, 87.5f);
System.out.println("姓名:" + student.name);
System.out.println("年龄:" + student.age);
System.out.println("语文成绩:" + student.chinese);
System.out.println("数学成绩:" + student.math);
System.out.println("英语成绩:" + student.english);
System.out.println("总成绩:" + student.totalScore);
System.out.println("平均成绩:" + student.averageScore);
}
```
运行该程序,将会输出以下结果:
```
姓名:张三
年龄:18
语文成绩:89.5
数学成绩:93.0
英语成绩:87.5
总成绩:270.0
平均成绩:90.0
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)