0

我正在尝试设置一个程序的一部分,该程序允许人们根据交易日期查看帐户的交易。用户输入月日和年以查看交易并将其与与给定交易相关的日期进行比较。我很难编写确定日期是否相等的代码行

if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
                        if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
                            if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){

我收到的错误是“无法在原始类型 int 上调用 compareTo(int)”,请参见下面的完整代码:

System.out.println("Enter the account number of the account that you want to view transactions for");
            number=keyboard.nextLong();
            System.out.println("Enter the month day and year of the date that the transactions were completed");
            int month=keyboard.nextInt()-1;
            int day=keyboard.nextInt();
            int year=keyboard.nextInt();
            found=false;
            try{
            for(int i=0;i<aBank.getAccounts().size();i++){
                if (aBank.getAccounts().get(i).getAccountNumber().compareTo(number)==0){
                    found=true;
                    System.out.println("Below is a list of transactions completed on "+month+ "/" +day+ "/" +year);
                    for (int j=0;j<aBank.getAccounts().get(i).getTransaction().size();j++){
                    if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH).compareTo(month)==0){
                        if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.DAY_OF_MONTH).compareTo(day)==0){
                            if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR).compareTo(year)==0){
                                aBank.getAccounts().get(i).getTransaction().get(j).toString();
                                break;
                            }
                        }

                    }

                }
4

4 回答 4

1

对于原始值,您可以使用==

aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year
于 2011-06-06T03:40:22.177 回答
1

只需使用:

aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month

于 2011-06-06T03:40:28.633 回答
1

如果所有XYZ.getTransDate()返回日历,则
XYZ.getTransDate().get(SOMETHING)返回原始int。基元没有comapreTo方法,只需使用==

所以而不是XYZ.getTransDate().get(MONTH).compareTo(month) == 0使用 XYZ.getTransDate().get(MONTH) == month

于 2011-06-06T03:48:28.893 回答
0

这应该有效:

Calendar transDate = aBank.getAccounts().get(i).getTransaction().get(j).getTransDate();
if (transDate.get(Calendar.YEAR) == year &&
    transDate.get(Calendar.MONTH) == month &&
    transDate.get(Calendar.DAY_OF_MONTH) == day) {

    // do something
}

如果您使用Apache Commons Lang 之类的东西会更好:

if (DateUtils.isSameDay(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(),
                        Calendar.getInstance().set(year, month, day)) {
    ...
}
于 2011-06-06T13:50:12.020 回答