【问题标题】:can't find why loop don't go inside my condition in my java serrvlet [closed]在我的 java servlet 中找不到循环不进入我的条件的原因 [关闭]
【发布时间】:2013-04-08 23:50:05
【问题描述】:
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    WorldDBManager DB = new WorldDBManager();
    String choices = request.getParameter("selectchoice");
    List<WorlPopulationInfo> country = new ArrayList<>();

    country = DB.getResultAsArrayList("world", "select * from country");


    StringBuffer strB = new StringBuffer();


    for(int i=0;i<country.size();i++){
        if(country.get(i).countryName == choices){
            strB.append("<option selected='selected'>" + country.get(i).countryName+"</option>");
            System.out.println(choices + " pareil " + country.get(i).countryName);
        }else if(country.get(i).countryName != choices){
            strB.append("<option>" + country.get(i).countryName+"</option>");
            System.out.println(choices + " " + country.get(i).countryName);
        }
    }


    request.setAttribute("country", strB);




    getServletContext().getRequestDispatcher("/index.jsp").forward(request,  response);

}

我不明白为什么他不去第一个如果条件我知道变量选择的值存在于我的数据库中,通过执行 System.println。我只是不明白为什么无视我的平等。如果有人可以解释我做错了什么。谢谢。

【问题讨论】:

标签: java jakarta-ee servlets web


【解决方案1】:

试试-

if(country.get(i).countryName.equals(choices)){

那里不需要else If,只需要else就足够了

 if(country.get(i).countryName.equals(choices)){
            strB.append("<option selected='selected'>" + country.get(i).countryName+"</option>");
            System.out.println(choices + " pareil " + country.get(i).countryName);
        }else{
            strB.append("<option>" + country.get(i).countryName+"</option>");
            System.out.println(choices + " " + country.get(i).countryName);
        }

【讨论】:

  • 哦,该死的,我忘了一个哈哈,我觉得自己很愚蠢
【解决方案2】:

使用 .equals() 进行字符串比较。

【讨论】:

    【解决方案3】:

    我认为您不能将字符串与 == 进行比较(也许在 1.7 中)。你必须使用

    if(country.get(i).countryName.equals(choices)){}
    

    【讨论】:

    • 是的,我完全忘记了那个。我不知道我在想什么,然后卡在那里 20-30 分钟
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2012-03-23
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多