第七章第十七题(对学生排序)(Sort students)
-
**7.17(对学生排序)编写一个程序,提示用户输入学生个数、学生姓名和他们的成绩,然后按照学生成绩的降序打印学生的姓名。假定姓名是不包含空格的字符串,使用Scanner类的next()方法来读取姓名。
**7.17(Sort students)Write a program to prompt the user to input the number of students, the names of students and their grades, and then print the names of students according to the descending order of students’ scores. Assuming that the name is a string without spaces, use the next () method of the scanner class to read the name. -
参考代码:
package chapter07; import java.util.Scanner; public class Code_17 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("请输入学生的个数:"); int number = input.nextInt(); int[] score = new int[number]; String[] name = new String[number]; for (int i = 0;i < number;i++){ System.out.print("请输入学生姓名:"); name[i] = input.next(); System.out.print("请输入所有学生的成绩:"); score[i] = input.nextInt(); } for (int i = 0;i < number - 1;i++){ for (int j = 0;j < number - i - 1;j++){ if (score[j] > score[j + 1]){ int temp = score[j]; score[j] = score[j + 1]; score[j + 1] = temp; String str = name[j]; name[j] = name[j + 1]; name[j + 1] = str; } } } for (int i = 0;i < number;i++) System.out.println("学生的姓名:" + name[i] + "\n学生的成绩:" + score[i]); } }
-
结果显示:
请输入学生的个数:2 请输入学生姓名:jxh 请输入所有学生的成绩:90 请输入学生姓名:cxy 请输入所有学生的成绩:80 学生的姓名:cxy 学生的成绩:80 学生的姓名:jxh 学生的成绩:90 Process finished with exit code 0