【问题标题】:Looping Logical Error循环逻辑错误
【发布时间】:2015-12-21 06:30:59
【问题描述】:

我有一个包含值的表格 - 用户名、品牌和公司,表格中有详细信息

现在我正在尝试遍历循环以使用用户的品牌/名称和公司打印用户的名称。

但是当我在循环中尝试这个时,我没有得到正确的输出..

 public static void main(String arfs[])
 {
    List company = new ArrayList();
    List brand = new ArrayList();
    List name = new ArrayList();

    try
    {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("URL","root","root");
    Statement stmt = con.createStatement();
    ResultSet rs=stmt.executeQuery("select * from fashion");
    while(rs.next())
    {
        name.add(rs.getString("Username"));
        brand.add(rs.getString("Brand"));
        company.add(rs.getString("Company"));
    }



    for(int i=0; i<name.size();i++)
    {
        if((name.get(i)!=null)&&(brand.get(i)!=null))
        {
            System.out.println("----Brand------");
            System.out.println(brand.get(i));

        }
        if((name.get(i)!=null)&&(company.get(i)!=null))
        {
             System.out.println("----Company-----");
            System.out.println(company.get(i));
        }

    }


    }
    catch(Exception e)
    {

    }

}

当我运行此代码时,只打印品牌而不打印公司..谁能帮帮我..?

【问题讨论】:

  • 我看到前两家公司是null。所以条件被评估为false..
  • company 在arraylist中可以为空!!!
  • 我们能看到实际的输出吗?
  • 同意@KumaresanPerumal 如果条件阻塞了输出​​。所以删除那些。也不要将名称作为主键。 (如果用户名是主键)。
  • 正如其他人所写,问题出在您的 If 条件中(这是纯逻辑,而字段为空,不会打印任何内容)顺便说一句,我也认为该逻辑将表的每一行保存 1 到 3单独的列表不是一个好主意.. 更好的是例如。制作自己的类并保存到列表或地图中,其他方式可以是通过一个数组列表,例如。 (每条记录将作为 1 行)等。..

标签: java list loops


【解决方案1】:

你删除你的条件。您的公司字段为空,因此“如果”条件会打印任何内容。

for(int i=0; i<name.size();i++)
    {

            System.out.println("----Brand------");
            System.out.println(brand.get(i));
            System.out.println("----Company-----");
            System.out.println(company.get(i));

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多