代码之家  ›  专栏  ›  技术社区  ›  George

“数据库”中不存在字符串时无法捕获异常

  •  -1
  • George  · 技术社区  · 8 年前

    我有这样的想法:

    ...
    while (itr.hasNext()) {
    ...
    try {
    
        if (userInput.equalsIgnoreCase(theData.getName())
            || (country.getName().toString()).equalsIgnoreCase(theData.getName()))
           {
    
            result = new Country(PointT, dist);
            break;
    
          } else {
    
            for (int i = 0; i < repl.size(); i++) { 
    
              if (repl.get(i).toString().contains(theData.getName())) {
    
                theName = true;
                result = new Country(PointTt, dist, theName);
                break;
              } else if (theParts.get(i).toString().equalsIgnoreCase(theData.getName())) {
                result = new Country(PointT, dist);
                break;
              } 
            } 
    
    
          }
        } catch (NoSuchElementException ex) {
          logger.error("Does not exist in database", ex);
          throw ex;
        } catch (NullPointerException ex) {
    
          logger.error("Does not exist in database", ex);
          throw ex;
        }catch (Exception ex) {
          logger.error("Does not exist in database", ex);
          throw ex;
        }
    }
    ...
    

    theData.getName() 这个 userInput country.getName() repl.get(i) List<String> , theParts.get(i) 列表(<);字符串(>);

    (theData.getName()) .

    读取数据

    为了阅读 theData :

    我正在使用 FileInputStream fis = new FileInputStream(filelocation);

    然后,仅提取字符串并存储它们:

    ArrayList<String> theNames = new ArrayList<String>();

    然后我合并 theNames 与其他迭代器一起创建

    ArrayList<theNamesLoc> theNamesLocList = new ArrayList<theNamesLoc>();

    这是我应用的数组列表:

    Iterator<TheNamesLoc> itr = theNamesLocList.iterator();
    
    while (itr.hasNext()) {
    
    ..}
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Parijat Purohit    8 年前

    编辑:

    1. 给定输入是列表中任何字符串的一部分(例如:输入为“xyz”,列表包含元素“axyzw”)。
    2. 输入与列表中的一项完全匹配。

    boolean isPresent = false;
    for(String elem: list){
        if(elem.contains("xyz")){//check each string if it contains the element
            isPresent = true;
            break;
        }
    }
    if(!isPresent){
        throw new NoSuchElementException("Element wasn't found in the list");
    }
    

    第二种情况:

    if(!list.contains("xyz")){
        throw new NoSuchElementException("Element not found");
    }
    

    最终,您必须“抛出”异常,该异常稍后可以在需要的地方捕获。

    if (repl.get(i).toString().contains(theData.getName())) {
    ....
    } else{
        throw new NoSuchElementException(args...);
    }