2015-11-07 200 views
0

好吧,这不是我在Java中的第一个循环,我已经编写了一年多的时间,但由于某些原因,我似乎无法在这里得到这个想法,有一个抽屉,其中包含类别,每个类别都可以/不能有描述,如果用户试图添加一个存在的类别,程序首先检查描述是否相同,如果是,它会提示用户更改描述或类别,下面是我的代码,我第一次运行它,它第二次正常工作,它提示用户的用户,但也增加了类别而不是返回,任何帮助将不胜感激。 `For循环和如果语句混淆

private void addCategory(String category, String description) 
    { 
    if(drawer.getItems().isEmpty()) { 
     addDrawerItem(category, description); 


    }else { 
     for (int i = 0; i < drawer.getItems().size(); i++) { 

      if (category.toUpperCase().equals(drawer.getItem(i).getTextPrimary()) 
        && description.equals(drawer.getItem(i).getTextSecondary())) { 
       Toast.makeText(getBaseContext(), "Category with same description exists", Toast.LENGTH_SHORT).show(); 

      }else { 

        addDrawerItem(category, description); 
        return; 


      } 

     } 

    } 
}` 
+0

我认为'toUpperCase()'可以让你试图比较时出现问题 –

+0

getTextPrimary中的字符串在Caps中,因此我必须将其转换为大写字母,然后才能进行比较,否则返回false返回所有搜索结果 –

回答

0

这应该更好地工作:

private void addCategory(String category, String description) { 
    if (drawer.getItems().isEmpty()) { 
     addDrawerItem(category, description); 
    } else { 
     for (int i = 0; i < drawer.getItems().size()); i++) { 
      if (category.toUpperCase().equals(drawer.getItem(i).getTextPrimary().toUpperCase()) 
        && description.equals(drawer.getItem(i).getTextSecondary())) { 
       Toast.makeText(getBaseContext(), "Category with same description exists", Toast.LENGTH_SHORT).show(); 
       return; 
      } 
     } 

     addDrawerItem(category, description); 
    } 
} 

环路仅用于查找匹配条目。只有在找不到匹配的情况下才会添加新条目。我还添加了一个toUpperCase()调用,以确保类别测试能够按照您明显打算的方式工作。

+0

和它只是工作,非常感谢,它开始让我紧张。 –