2015-12-02 47 views
1

我有一個包含以下字段的對象的ArrayList:寫作搜索標準的Java

  • INT用戶ID
  • INT帳戶ID
  • 字符串accountHoldersName
  • 字符串ACCOUNTTYPE
  • 雙平衡
  • 字符串accountStatus

在我的程序中的某處,我必須要求用戶輸入每個字段的搜索條件。如果用戶將字段留空,則不應將其包含在搜索中。即如果用戶沒有指定賬戶持有人姓名,則應顯示與賬戶持有人姓名相符的其他標準的所有賬戶。

我不知道如何寫一個if()進行這樣的比較,我可能沒有比較值。

String acT; 
String holdersN; 
String acStat; 
int usrId = 0, acId = 0; 
double bal = 0; 

System.out.println("SEARCH MENU:\n"); 
System.out.print("Account ID : "); 
acId = sc.nextInt(); 
System.out.print("User ID: "); 
usrId = sc.nextInt(); 
System.out.print("Balance: "); 
bal = sc.nextDouble(); 
System.out.print("Holders Name : "); 
holdersN = sc.nextLine(); 
System.out.print("Type (Savings Current): "); 
acT = sc.nextLine(); 
sc.nextLine(); 
System.out.print("Status: "); 
acStat = sc.nextLine(); 

System.out.println("\n===== SEARCH RESULTS =====\n"); 
System.out.println("Account ID\tUser ID\tHolders Name\tType\tBalance\tStatus"); 
// accountsInfo is my ArrayList 
for(int j = 0;j < accountsInfo.size(); j++) 
{ 
    AccountInformation ac3 =(AccountInformation)accountsInfo.get(j); 
    if(// i dont know how to write search criteria here which will compare only those values that are provided by user) 
    { 
     System.out.println(ac3.accountID +"\t"+ ac3.userID +"\t"+ ac3.holdersName +"\t"+ ac3.accountType +"\t"+ ac3.balance +"\t"+ ac3.accountStatus); 
    } 
} 

回答

1

嘗試OR條件:

if((acId == -1 || ac3.accountID == acId) && (acStat == null/*Empty string*/ || acStat.equals(ac3.accountStatus)) && (so on)) { 
    System.out.println(ac3.accountID +"\t"+ ac3.userID +"\t"+ ac3.holdersName +"\t"+ ac3.accountType +"\t"+ ac3.balance +"\t"+ ac3.accountStatus); 
} 

希望這有助於!

0

你可能需要做一些空值檢查明確地通過!= null或含蓄:

if (ac3.holdersName.equalsIgnoreCase(holdersN)) { 
     .... 
    } 

閱讀上String.equalsIgnoreCase()關於它是如何工作的更多信息。由於您在某些情況下使用int,因此您需要檢查它們是否合理,因爲它們不能爲空。