英文:
It's a compilation in the student list class, but it's not aligned
问题
public void sortById() {
int i, j, min;
for (i = 0; i < number - 1; i++) {
min = i;
for (j = i + 1; j < number; j++) {
if (StudentList[j].getId() < StudentList[min].getId()) {
min = j;
}
swap(StudentList[min], StudentList[i]);
}
}
}
public void swap(StudentList std1, StudentList std2) {
Student st = new Student(0, "", 0);
st = std1;
std1 = std2;
std2 = st;
}
如果我编译上述代码,没有错误和异常,并且输出是不对齐的,那么你要如何解决这个问题?
英文:
public void sortById() {
int i, j, min;
for(i = 0 ; i < number - 1; i++) {
min = i;
for(j = i + 1; j < number; j++) {
if (StudentList[j].getId() < StudentList[min].getId()) {
min = j;
}
swap(StudentList[min].getId(), StudentList[i].getId());
}
}
}
public void swap(StudentList std1, StudentList std2) {
Student st = new Student(0,"",0);
st = std1;
std1 = std2;
std2 = st;
}
If I compile the code above, there is no error and an exception, and it comes out unaligned, so how do you solve it?
答案1
得分: 1
我不太理解你所说的“它变成了不对齐”,但你可能遇到问题,因为在你的 swap
方法中实际上没有交换任何内容。
而是应该像这样将对象的索引传递给方法:
public void swap(int a, int b) {
StudentList temp = studentList[a];
studentList[a] = studentList[b];
studentList[b] = temp;
}
然后以这种方式调用该方法:
swap(min, i);
英文:
I don't really understand what you mean by "it comes out unaligned", but you are probably running into problems because you are not actually swapping anything in your swap
method.
Instead if passing the objects into the method, you need to pass the indexes of those objects, like this:
public void swap(int a, int b) {
StudentList temp = studentList[a];
studentList[a] = studentList[b];
studentList[b] = temp;
}
And call the method this way:
swap(min, i);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论