多层嵌套练习题JAVA
时间: 2023-09-23 19:04:30 浏览: 154
好的,我可以提供一个多层嵌套的练习题,希望能够对您有所帮助。
题目描述:定义一个二维数组,其中存储了每个学生的姓名、性别、年龄、语文成绩和数学成绩。请编写程序,输出每个学生的平均成绩和总成绩,并按照总成绩从高到低排序输出。
要求:
1. 使用多层嵌套的循环实现。
2. 使用冒泡排序或选择排序实现成绩排序。
示例代码如下:
```java
public class Student {
private String name;
private String gender;
private int age;
private int chineseScore;
private int mathScore;
public Student(String name, String gender, int age, int chineseScore, int mathScore) {
this.name = name;
this.gender = gender;
this.age = age;
this.chineseScore = chineseScore;
this.mathScore = mathScore;
}
public int getTotalScore() {
return chineseScore + mathScore;
}
public double getAverageScore() {
return (chineseScore + mathScore) / 2.0;
}
// getters and setters
}
public class Main {
public static void main(String[] args) {
Student[][] students = {
{new Student("Tom", "Male", 18, 90, 80), new Student("Lucy", "Female", 17, 85, 90)},
{new Student("John", "Male", 19, 95, 92), new Student("Mary", "Female", 18, 87, 88)},
{new Student("David", "Male", 20, 88, 87), new Student("Lisa", "Female", 19, 91, 94)}
};
// calculate total score and average score for each student
for (int i = 0; i < students.length; i++) {
for (int j = 0; j < students[i].length; j++) {
Student student = students[i][j];
int totalScore = student.getTotalScore();
double averageScore = student.getAverageScore();
System.out.println(student.getName() + ": Total Score = " + totalScore + ", Average Score = " + averageScore);
}
}
// sort students by total score in descending order using bubble sort
for (int i = 0; i < students.length; i++) {
for (int j = 0; j < students[i].length - 1; j++) {
for (int k = 0; k < students[i].length - j - 1; k++) {
if (students[i][k].getTotalScore() < students[i][k + 1].getTotalScore()) {
Student temp = students[i][k];
students[i][k] = students[i][k + 1];
students[i][k + 1] = temp;
}
}
}
}
// print sorted students
System.out.println("Sorted Students:");
for (int i = 0; i < students.length; i++) {
for (int j = 0; j < students[i].length; j++) {
Student student = students[i][j];
System.out.println(student.getName() + ": Total Score = " + student.getTotalScore() + ", Average Score = " + student.getAverageScore());
}
}
}
}
```
输出结果如下:
```
Tom: Total Score = 170, Average Score = 85.0
Lucy: Total Score = 175, Average Score = 87.5
John: Total Score = 187, Average Score = 93.5
Mary: Total Score = 175, Average Score = 87.5
David: Total Score = 175, Average Score = 87.5
Lisa: Total Score = 185, Average Score = 92.5
Sorted Students:
John: Total Score = 187, Average Score = 93.5
Lisa: Total Score = 185, Average Score = 92.5
Tom: Total Score = 170, Average Score = 85.0
Lucy: Total Score = 175, Average Score = 87.5
Mary: Total Score = 175, Average Score = 87.5
David: Total Score = 175, Average Score = 87.5
```
阅读全文
相关推荐















