我正在做课堂作业。基本上,我们必须使用一维数组来显示学生的姓名、当前年级和学科。代码如下:
import java.util.*;
import java.util.Arrays;
public class sortStudents {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int numofstudents = input.nextInt();
String[] names = new String[numofstudents];
int[] array = new int[numofstudents];
String[] subject = new String[numofstudents];
for(int i = 0; i < numofstudents; i++) {
System.out.print("Enter the student's name: ");
names[i] = input.next();
System.out.print("Enter the student's score: ");
array[i] = input.nextInt();
System.out.print("Enter the subject: ");
subject[i] = input.next();
}
selectionSort(names, array, subject);
System.out.println(names[i] + array[i] + subject[i]);
}
public static void selectionSort(String[] names, int[] array, String[] subject) {
for(int i = array.length - 1; i >= 1; i--) {
String temp;
String classTemp = " ";
int currentMax = array[0];
int currentMaxIndex = 0;
for(int j = 1; j <= i; j++) {
if (currentMax > array[j]) {
currentMax = array[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
temp = names[currentMaxIndex];
names[currentMaxIndex] = names[i];
names[i] = temp;
array[currentMaxIndex] = array[i];
array[i] = currentMax;
subject[currentMaxIndex] = subject[i];
subject[i] = classTemp;
}
}
}
}
该错误是在第 22 行编译时产生的。我认为这是由于变量“i”没有在循环外初始化。但是当我将变量“i”放在循环之外时,我得到一个数组越界错误。任何解决此问题的帮助将不胜感激:)
PS我是这个网站的新手,所以如果我发布不正确,我很抱歉。