救救我:java程序求助啊

来源:百度知道 编辑:UC知道 时间:2024/06/05 19:13:09
class Date {
public int year, month, day;
Date(int y, int m, int d) {
year = y;
month = m;
day = d;
}

public String toString() {
return (year + "-" + month + "-" +day);
}
public int compare(Date d) {
if(year > d.year) {
return 1;
} else if(year < d.year){
return -1;
} else if(month > d.month) {
return 1;
} else if(month > d.month) {
return -1;
} else if(day > d.day) {
return 1;
} else if(day < d.day) {
return -1;
} else {
return 0;
}
}
}

public class TestDate {
public static void main(String[] args) {
Date[] d = new Date[5];
d[0] = new Date(3000, 3 ,3);
d[1] = new Date(2000, 1, 1);
d[2] = new Date(2001, 1, 1);
d[3] = new Date(1997, 6, 1);
d[4] = new Date(2008, 4, 5);

Date

一楼说的对

楼主不要执迷不悟了。

public static int search(Date[] a, Date c ) {
if(a.length <= 0) { return -1; }
int sPos = 0;
int ePos = a.length - 1;
int m = (sPos + ePos) / 2;
while(sPos <= ePos) {
if(c.compare(a[m]) == 0) { return m; }
if(c.compare(a[m]) > 0 ) { sPos = m + 1; }
if(c.compare(a[m]) < 0) { ePos = m - 1; }
m = (sPos + ePos) /2;
}
// 注意这里,不知道你要返回什么,但是这里就是无限返回-1.自己在好好想想
return -1;

看看search的最后一句,你老是让它return -1;难道要它返回-2?

while(sPos <= ePos) {
if(c.compare(a[m]) == 0) { System.out.println("==");return m; }
if(c.compare(a[m]) > 0 ) { sPos = m + 1; System.out.println(">");}
if(c.compare(a[m]) < 0) { ePos = m - 1; System.out.println("<");}//执行一次你的程序,这里显示了<
m = (sPos + ePos) /2;
}