2011-06-06 192 views
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; 
          } 
         } 

        } 

       } 

回答

1

爲原始值,您可以只使用==

aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year 
1

只需使用:

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

1

如果所有XYZ.getTransDate()回報日曆,然後
XYZ.getTransDate().get(SOMETHING)返回原始int。基元沒有comapreTo方法,只要使用==

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

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更好: