我对编程有些陌生,我正在尝试显示打印的对象数组。我不断收到此编译错误:
SchoolTextBookSort.java:90:错误:找不到符号 System.out.println(textBooks [x] .bubbleSortAuthor()+“”); ^ 符号:方法bubbleSortAuthor() 位置:班级SchoolTextBook 1个错误
这是导致错误的代码。有人可以帮我吗?
if (response.equals("AUTHOR"))
{
for (int x = 0; x < textBooks.length; ++x)
{
System.out.println(textBooks[x].bubbleSortAuthor() + " ");
}
System.out.println();
}
else
System.out.println("Invalid Response.");
}
public static void bubbleSortAuthor(SchoolTextBook[] array)
{
int a, b;
SchoolTextBook temp;
int highSubscript = array.length - 1;
for (a = 0; a < highSubscript; ++a)
for(b = 0; b < highSubscript; ++b)
if (array[b].getAuthorName().compareTo(array[b + 1].getAuthorName()) < 0)
{
temp = array[b];
array[b] = array[b + 1];
array[b + 1] = temp;
}
}
答案 0 :(得分:0)
您需要通过将其传递给数组而不是在数组上进行调用来调用bubbleSortAuthor。
赞:
bubbleSortAuthor(textBooks);
它是静态的,但是将数组作为参数,并且是属于您所在类的方法,因此您不需要
YourClassName.bubbleSortAuthor(textBooks);
来自同一个班级
此外,它返回空值,您将无法打印空值。您应该再次遍历该数组以对其排序后进行打印。
答案 1 :(得分:0)
您有一些小错误,如下所述。
textbooks
数组传递给方法bubbleSortAuthor(SchoolTextBook[])
。似乎您正在尝试在数组中的SchoolTextBook对象上调用该方法。您不能从类对象调用静态方法。您必须像
这样称呼它bubbleSortAuthor(array); // if calling it from inside the class
或使用类名
SchoolTextBook.bubbleSortAuthor(array); // from anywhere - if declared public
您的气泡排序算法不正确。内部for循环应写为:
for(b = 0; b < highSubscript -a; ++b) { // you were missing the -a
方法 .compareTo(String)
public int compareTo(String anotherString)
按字典顺序比较两个字符串。比较是基于字符串中每个字符的Unicode值。在字典上比较此String对象表示的字符序列与自变量字符串表示的字符序列。如果此String对象在字典上在参数字符串之前,则结果为负整数。如果此String对象在字典上跟随自变量字符串,则结果为正整数。如果字符串相等,则结果为零;否则,结果为零。当equals(Object)方法返回true时,compareTo确切返回0。
通过使用下面的>
,我们以升序排序。这也意味着大写字母位于小写字母(ASCII)之前。如果您不希望这种行为,可以在比较之前将.toLowerCase()
应用于元素。
有关.compareTo()方法here
的更多信息这是更正的代码:
if (response.equals("AUTHOR")) {
for (int x = 0; x < textBooks.length; ++x) {
// if textBooks is 2D array of SchoolTextBook objects then call it like this
bubbleSortAuthor(textBooks[x]);
}
// if textBooks is 1D array of SchoolTextBook objects then you don't need the
// above for loop. You could just write:
// bubbleSortAuthor(textBooks);
// print results
for(SchoolTextBook textBook : textBooks) {
System.out.println(textBook.getAuthorName());
}
} else {
System.out.println("Invalid Response.");
}
public static void bubbleSortAuthor(SchoolTextBook[] array) {
int a, b, arrayLength = array.length;
SchoolTextBook temp;
for (a = 0; a < arrayLength - 1; ++a) {
for(b = 0; b < arrayLength - 1 - a; ++b) {
if (array[b].getAuthorName().compareTo(array[b + 1].getAuthorName()) > 0) {
temp = array[b];
array[b] = array[b + 1];
array[b + 1] = temp;
}
}
}
}