【问题标题】:How to return null if String .contains method doesn't fit?如果 String .contains 方法不适合,如何返回 null?
【发布时间】:2016-03-16 11:50:38
【问题描述】:

如果没有标题包含 wordInTitle 的书,或者 wordInTitle 为 null 或“”,我有此代码并希望返回 null。我可以设法为 null 和 "" 做到这一点,但如果没有包含 wordInTitle 的书则不行。有人可以帮帮我吗?

public String[] getBookTitlesContaining(String wordInTitle)
{
    int nBooks = 0;
    String[] bookTitle = new String[nBooks];

    for (Book booksTitles : inventory)
    {
        if(booksTitles.getTitle().toLowerCase().contains(wordInTitle.toLowerCase()))
        {
            nBooks++;
        }
    }

    int titleB = 0;
    bookTitle = new String[nBooks];

    for (Book booksTitles : inventory)
    {
        if(booksTitles.getTitle().toLowerCase().contains(wordInTitle.toLowerCase()))
        {
            bookTitle [titleB] = booksTitles.getTitle();
            titleB++;
        }
    }

    if ((wordInTitle == null) || (wordInTitle == "")) 
    {
        return null;
    }

    return bookTitle;

提前致谢

【问题讨论】:

    标签: java null contains


    【解决方案1】:

    更改此if 以包含没有匹配书籍的情况:

    if ((wordInTitle == null) || (wordInTitle == "") || (nBooks == 0)) 
    {
        return null;
    }
    

    【讨论】:

      【解决方案2】:

      统计有书名的书数后,如果计数为0,可以返回null;

      public String[] getBookTitlesContaining(String wordInTitle)
      {
          int nBooks = 0;
          String[] bookTitle = new String[nBooks];
      
          for (Book booksTitles : inventory)
          {
              if(booksTitles.getTitle().toLowerCase().contains(wordInTitle.toLowerCase()))
              {
                  nBooks++;
              }
          }
      
          if (nBooks == 0) return null;
      

      【讨论】:

      • 这个得到“缺少返回语句”错误@controlAltDel
      猜你喜欢
      • 1970-01-01
      • 2019-06-24
      • 2014-02-07
      • 1970-01-01
      • 2023-03-31
      • 2015-09-01
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多