I am trying to set up part of a program that allows a person to view transactions of an account based on the date of the transaction. The user enters the month day and year to view transactions and that is compared to the date that is connected to a given transaction. I am having difficult writing the lines of code that determine if the date is equal
if(aBank.getAccounts().get(i).getTransaction().get(j).getTransDat开发者_如何学Goe().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){
The error that I am receiving is "cannot invoke compareTo(int) on the primitive type int" see full code below:
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;
}
}
}
}
For primitive values you can just use ==
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.YEAR)==year
Just use:
aBank.getAccounts().get(i).getTransaction().get(j).getTransDate().get(Calendar.MONTH) == month
If all of the XYZ.getTransDate()
returns Calendar, then
XYZ.getTransDate().get(SOMETHING)
returns primitive int
. Primitives do not have comapreTo method, just use ==
so instead of XYZ.getTransDate().get(MONTH).compareTo(month) == 0
use
XYZ.getTransDate().get(MONTH) == month
This should work:
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
}
Even better if you use something like Apache Commons Lang:
if (DateUtils.isSameDay(aBank.getAccounts().get(i).getTransaction().get(j).getTransDate(),
Calendar.getInstance().set(year, month, day)) {
...
}
精彩评论