我在做一个班级作业。基本上,我们必须使用一维数组来显示学生的姓名、当前成绩和科目。代码如下:
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“放在循环之外时,我得到了一个数组越界错误。如果能帮助我们解决这个问题,我们将不胜感激:)
附言:我是新来这个网站的,所以如果我发错了帖子,我向你道歉。
发布于 2013-07-17 05:55:00
当您到达System.out.println(names[i] + array[i] + subject[i]);时,作用域中没有i变量。
for循环中。for循环来遍历数组。for(int j= 0;j< numOfStudents;j++) {System.out.println(i+ arrayi + subjecti);}
https://stackoverflow.com/questions/17687600
复制相似问题