[英]Cannot call instance method from static method
我有这个类,我只需要帮助方法中的toString()
来实际显示结果。 它给了我一个错误,我不能在静态上下文中使用getName()
或getId()
:
public static void bubbleSort(Student[] array)
{
for(int i=(array.length); i>0; i--)
for(int j=1; j<(array.length-i); j++)
if(array[j].getName().compareTo(
array[j+1].getName())<0) {
Student Temp = array[j];
array[j] = array[j+1];
array[j+1] = Temp;
}
String s = null;
for (int i=0; i<array.length; i++) {
// the error is here under the getName and getId
s= s+ getName()+" "+ getId() ;
}
System.out.print (s);
}
代替:
s= s+ getName()+" "+ getId() ;
你可能需要这样做:
s= s+ array[i].getName()+" "+ array[i].getId() ;
并且如上面的评论所述,使用:
String s = "";
我想你想打印你之前排序的Student
的名字和ID。
public static void bubbleSort(Student[] array)
{
for(int i=(array.length); i>0; i--)
{
for(int j=1; j<(array.length-i); j++)
{
if( array[j].getName().compareTo(array[j+1].getName())<0)
{
Student Temp = array[j];
array[j] = array[j+1];
array[j+1] = Temp;
}
}
}
String s = ""; // should not be null
for (int i = 0; i < array.length; i++)
{
s = s + array[i].getName()+" "+ array[i].getId(); // changed this line
System.out.print (s); // moved this into the loop because I think this makes more sense
}
}
getName()
和getID()
属于Student
对象,而不是定义bubbleSort()
的类的方法。
您可能需要array[i].getName()
和array[i].getId()
而不是getName()
和getId()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.