样本输入:
1年级学生:75
学生2年级:85
学生3年级:90
学生4年级:85
5年级学生:90
示例输出:
前1名:学生3
学生5
前2名:学生2
学生4
前3名:学生1
Scanner sc = new Scanner(System.in);
int[] grade = new int[5];
int[] gradeClone;
for(int i = 1; i <= 5; i++){
System.out.print("Enter student " + i + " grade: ");
grade[i-1] = sc.nextInt();
}
gradeClone = grade.clone();
int failed = 0;
for(int x = 1; x <= 5; x++){
System.out.print("Student " + x + " Remark = ");
if(grade[x-1] >= 60){
System.out.println(" Passed");
}else{
System.out.println(" Failed");
failed++;
}
}
int total = 0;
for(int a = 0; a < 5; a++){
total += grade[a];
}
int temp;
for(int j = 0; j < 5; j++){
for(int k = 1; k < 5; k++){
if(grade[k-1] < grade[k] ){
temp = grade[k-1];
grade[k-1] = grade[k];
grade[k] = temp;
}
}
}
String ranking = failed <= 4 ? " then the ranking is: ": " all failed";
System.out.println("The average is " + total/5 + ranking );
int topCount = 5-failed;
for(int a = 1; a < 5; a++){
if(gradeClone[a-1] == gradeClone[a]){
--topCount;
}
}
for(int i = 0; i < 5; i++){
System.out.println(gradeClone[i]);
}
我无法提出一种对他们进行排名的方法。我应该怎么做?
答案 0 :(得分:0)
我认为您需要这样的东西?从最高分到最低/最低到最高排名。顺便说一下,我对成绩进行了硬编码,您可以将其更改为用户输入。
int[] grade = {50,60,30,40,80};
int temp;
for (int i = 0; i < grade.length; i++)
{
for (int j = i + 1; j < grade.length; j++)
{
if (grade[i] > grade[j])
{
temp = grade[i];
grade[i] = grade[j];
grade[j] = temp;
}
}
}
System.out.println("Rank from lowest to highest:");
for (int i = 0; i < grade.length - 1; i++)
{
System.out.print(grade[i] + "\n");
}
System.out.print(grade[grade.length - 1]);
System.out.println("\n\nRank from highest to lowest:");
for (int i = 4; i >= 0; i--)
{
System.out.print(grade[i] + "\n");
}