【问题标题】:writing search criteria java编写搜索条件java
【发布时间】:2015-12-02 18:15:09
【问题描述】:

我有一个包含以下字段的对象数组列表:

  • int 用户 ID
  • int accountID
  • 字符串 accountHoldersName
  • 字符串帐户类型
  • 双平衡
  • 字符串帐户状态

在我的程序中,我必须要求用户为每个字段输入搜索条件。如果用户将字段留空,则不应将其包含在搜索中。即,如果用户未指定帐户持有人姓名,则应显示所有符合其他条件且具有帐户持有人姓名的帐户。

我不知道如何编写 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);
    }
}

【问题讨论】:

    标签: java


    【解决方案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);
    }
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      您可能需要通过!= null 显式或隐式地进行一些空值检查:

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

      阅读String.equalsIgnoreCase() 以获取有关其工作原理的更多信息。由于您在某些情况下使用int,因此您需要检查它们是否是合理的值,因为它们不能为空。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-21
        • 1970-01-01
        • 1970-01-01
        • 2012-01-14
        • 2019-09-16
        • 2017-10-13
        • 1970-01-01
        相关资源
        最近更新 更多