请帮助根据最高数字/分数排序字符串(顺便说一句,根据我们的指导,我们不能使用"arrays.sort")
package test;
import java.util.Scanner;
public class Test
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String [] name = new String[10];
int [] score = new int [10];
int temp = 0;
//Displaying elements of original array
for (int i = 0; i < 10; i++) {
System.out.println("nNumber " + (i+1));
System.out.print("Input your name: ");
name[i] = sc.next();
System.out.print("Input your score: ");
score[i] = sc.nextInt();
}
//Sort the array in descending order
for (int i = 0; i < score.length; i++) {
for (int j = i+1; j < score.length; j++) {
if(score[i] < score[j]) {
temp = score[i];
score[i] = score[j];
score[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < 3; i++) {
System.out.println("the score of " + name[i] + " is " +score[i] + ". ");
}
}
}
输入示例如下
k1 96
k2 92
k3 94
k4 98
k5 91
k6 95
k7 90
k8 99
k9 93
k10 97
我想要的输出是这样的
k8 99
k4 98
k10 97
但实际情况是:
k1 99
k2 98
k3 97
请帮忙,我会喜欢一个简单的解释。谢谢你。
您有两个数组,一个名为name
,一个名为score
。
您只排序score
,而不更改name
。
我建议以下两种解决方案之一:
- 将名称和分数保存在对象中,并将其存储在一个数组中,并根据分数对该数组进行排序。
或
- 对
name
进行与score
相同的索引更改
我建议尝试实现第1条,因为名称和分数在概念上是同一对象的一部分,就像"年龄"one_answers";name"表示"人物"的对象
希望这对你有帮助,祝你作业顺利:-)
//Sort the array in descending order
for (int i = 0; i < score.length; i++) {
for (int j = i+1; j < score.length; j++) {
if(score[i] < score[j]) {
temp = score[i];
score[i] = score[j];
score[j] = temp;
}
}
}
在这里,当您对数组排序时,您只交换score
元素。要保持name
/score
配对,您应该交换偶数名称元素:
//Sort the array in descending order
for (int i = 0; i < score.length; i++) {
for (int j = i+1; j < score.length; j++) {
if(score[i] < score[j]) {
temp = score[i];
score[i] = score[j];
score[j] = temp;
tmp = name[i]
name[i] = name[j]
name[j] = tmp
}
}
}