public class Date {
int year,month,day;
public Date(int year,int month,int day) {
this.year=year;
this.month=month;
this.day=day;
}
public void bubbleSort(Date a[]) {
for(int i=a.length-1;i<=1;i--) {
for(int j=0;j<i;j++){
if(compare(a[j],a[j+1])==1){
Date temp;
temp=a[j] ;
a[j] =a[j+1] ;
a[j+1] =temp;
}
}
}
}
public int compare(Date a,Date b)
{
return a.year>b.year?1
:a.year<b.year?-1
:a.month>b.month?1
:a.month<b.month?-1
:a.day>b.day?1
:a.day<b.day?-1:0;
}
}如上,有一个bubbleSort方法
接下来我要调用bubbleSort
public class TestSort {
public static void main(String args[]){
Date[]day=new Date[5] ;
day[0]=new Date(2004,5,7);
day[1] =new Date(2004,5,8);
day[2] =new Date(2005,2,3);
day[3] =new Date(2008,4,6);
day[4] =new Date(2005,1,1);
* bubbleSort(day);
}}
结果打*的那一行出错了
说是:
找不到符号
符号:方法bubbleSort(Date[])
location:TestSort{5}问:
不是已经定义了bubbleSort 了吗,怎么不好调用啊!?
要怎么改正呢?
在此先谢谢各位了!
Date.bubbleSort(day);
public void bubbleSort(Date a[]) {
for(int i=a.length-1;i<=1;i--) {
for(int j=0;j<i;j++){
if(compare(a[j],a[j+1])==1){
Date temp;
temp=a[j] ;
a[j] =a[j+1] ;
a[j+1] =temp;
}
}
}
}
public int compare(Date a,Date b)
{
return a.year>b.year?1
:a.year<b.year?-1
:a.month>b.month?1
:a.month<b.month?-1
:a.day>b.day?1
:a.day<b.day?-1:0;
}}package com.meran.normalTest; public class Date {
int year,month,day;
public Date(int year,int month,int day) {
this.year=year;
this.month=month;
this.day=day;
} }
package com.meran.normalTest;public class TestSort {
public static void main(String args[]){
Date[]day=new Date[5] ;
day[0]=new Date(2004,5,7);
day[1] =new Date(2004,5,8);
day[2] =new Date(2005,2,3);
day[3] =new Date(2008,4,6);
day[4] =new Date(2005,1,1);
HandleDate hd=new HandleDate();
hd.bubbleSort(day);
} }
出现这个问题就是,你声明的bubbleSort是非static类型,必须要new一个Date对象的实例,比如是d,然后通过这个实例来调用d.bubbleSort()才可以,不能像C语言那样直接在main里面像调用库函数一样。如果想要不new对象调用,给你贴一下代码,方法都改成static
public class Date {
int year, month, day; public Date(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
} public static void bubbleSort(Date a[]) {
for (int i = a.length - 1; i <= 1; i--) {
for (int j = 0; j < i; j++) {
if (compare(a[j], a[j + 1]) == 1) {
Date temp;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
} } public static int compare(Date a, Date b) {
return a.year > b.year ? 1 : a.year < b.year ? -1
: a.month > b.month ? 1 : a.month < b.month ? -1
: a.day > b.day ? 1 : a.day < b.day ? -1 : 0; }
}
public class TestSort {
public static void main(String args[]){
Date[]day=new Date[5] ;
day[0]=new Date(2004,5,7);
day[1] =new Date(2004,5,8);
day[2] =new Date(2005,2,3);
day[3] =new Date(2008,4,6);
day[4] =new Date(2005,1,1);
Date.bubbleSort(day);
}}