1.在此代码之前对数组进行了声明,但这不起作用
/*
* ------------------------Sorting students-------------------------
*/
import java.util.*;
public class Exercise6_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int students = input.nextInt();
String[] names = new String[students];
int[] scores = new int[students];
for(int i = 0; i < names.length; i++){
System.out.print("Enter student's name: ");
names[i] = input.nextLine();
System.out.print("Enter student's score: ");
scores[i] = input.nextInt();
}
Arrays.sort(scores);
for(int i = 0; i < scores.length; i++){
System.out.println (names[i]+" has "+scores[i]);
}
System.out.println("");
reverse(scores, names);
for(int i = 0; i < scores.length; i++){
System.out.println (names[i]+" has "+scores[i]);
}
}
public static void reverse(int[] numbers, String[] names) {
for(int i = 0; i < numbers.length; i++){
numbers[numbers.length - 1 - i] = numbers[i];
names[names.length - 1 - i] = names[i];
}
}
}
答案 0 :(得分:1)
这是固定版本
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int students = scanner.nextInt();
String[] names = new String[students];
int[] scores = new int[students];
for (int i = 0; i < names.length; i++) {
System.out.print("Enter student's name: ");
names[i] = scanner.next();
System.out.print("Enter student's score: ");
scores[i] = scanner.nextInt();
}
Arrays.sort(scores);
for (int i = 0; i < scores.length; i++) {
System.out.println(names[i] + " has " + scores[i]);
}
scanner.close();
}
输出
Enter the number of students: 2
Enter student's name: a1
Enter student's score: 11
Enter student's name: a2
Enter student's score: 22
a1 has 11
a2 has 22
<强> UPD 强>
如果您对names
进行排序,我猜你也应该调整scores
。