在C#中对具有多个变量类型的类实现冒泡排序
我有一个包含一些字符串和一些整数值的类。该程序需要使用冒泡排序来按名为 StudentID 的特定整数进行排序。
我遇到的问题是正确访问变量。我们需要将类中的变量保持为私有,因此除了实际类内部之外,无法直接从任何地方访问原始值。
我已经进行了类似的设置,
public class Student {
// PRIVATE strings and ints
public Student() {
// set variables to text fields
}
public void bubbleSort() {
int i, j, temp;
for (i = (x-1); i >= 0; i--) {
for (j = 1; j <= i; j++) {
if(x[j - 1] > students[j]) {
temp = x[j - 1];
x[j - 1] = x[j];
x[j] = temp;
}
}
}
}
}
对于每次出现的 X,我都需要具有 myStudent.studentID 的值。冒泡排序是要在类中实现的,但我不知道如何调用它。将所需字段设置为私有后,我找不到方法来提取要排序的信息。
I have a class that contains a few strings, as well as a few integer values. The program needs to use bubble sort to sort by a specific integer within called studentID.
The issue I'm coming across is accessing the variable properly. We are required to keep the variables within the class private, so the raw values aren't directly accessible from anywhere other than inside the actual class.
I've got something like this set up
public class Student {
// PRIVATE strings and ints
public Student() {
// set variables to text fields
}
public void bubbleSort() {
int i, j, temp;
for (i = (x-1); i >= 0; i--) {
for (j = 1; j <= i; j++) {
if(x[j - 1] > students[j]) {
temp = x[j - 1];
x[j - 1] = x[j];
x[j] = temp;
}
}
}
}
}
For every occurrence of X, I need to have the value of myStudent.studentID. The bubble sort is meant to be implemented within the class, but I can't figure out how to call it. With the needed fields set to private, I can find no way to pull the information to be sorted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Student 类中实现 IComparable 接口,然后使用 CompareTo() 而不是“<” bubbleBort 中的运算符。这将解决私有变量的问题。
经过这些更改后,BubbleSort 可以重写为静态泛型方法。
Implement IComparable interface in Student class, and then use CompareTo() instead of "<" operator in bubbleBort. This will solve the issue with private variable.
And after these changes BubbleSort can be rewritten as static generic method.
您可以使用属性将私有字段公开给外部。
如果你不被允许这样做,你应该和你的老师谈谈,因为那时不可能与班级互动。
You use properties to expose private fields to the outside.
If you aren't allowed to do that, you should talk with your teacher, as interacting with the class isn't possible then.