繁体   English   中英

为arraylist中的每个项目分配值

[英]assign value to every item in arraylist

我有一个用整数表示一个人的arraylist。 我想为每个第4个人分配一个表号,但是该数组列表中有4个以上的人,所以我想

  • 将接下来的4个人分配到另一张桌子,
  • 之后有4个人来到一张新桌子

我怎样才能做到这一点?

到目前为止,这是我尝试过的:

    try {
        String[] toernooi = toernooien2.getSelectedItem().toString().split(" ");

        PreparedStatement stat = con.prepareStatement("SELECT speler FROM fullhouse.inschrijving_toernooi WHERE IT_betaaldatum is not null AND toernooi = ?;");
        stat.setString(1, toernooi[0]);
        ResultSet resultaat = stat.executeQuery();
        ArrayList<Integer> array = new ArrayList<>();

        PreparedStatement stat2 = con.prepareStatement("INSERT INTO fullhouse.indeling (person,tablenumber,ronde) VALUES (?,?,?)");

        for (int i = 1; resultaat.next(); i++) {
            stat2.setInt(1, resultaat.getInt(1));
            array.add(resultaat.getInt(1));
            stat2.execute();

            for (Integer arrayitem : array) 
            {

            }

        }

有一个计数器,并在迭代时检查该计数器,并在第4次迭代时将计数器还原为1并分配给新表。

int counter=1;
for(Person p: list){
if(counter==4) {
//assing to a different table
counter=1;
continue;
}
//assign to an normal table
counter++;

}

您可以使用整数除法来避免担心其他变量或重置。 我已经用普通循环替换了迭代器,因为如果我们有一个计数器来对List进行计数,那么使用循环变量看起来更优雅:

private List<Integer> assign (List<Integer> guestList) {

    int size = guestList.size();

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

        guestList.add(i, i/4);

    }
        return guestList;
}

假设:

  • .size()方法获取来宾数
  • 第一个表号应为零
  • 输入列表的大小将不会超出整数除法范围

这是我的第一个答案-感谢评论:)

您应该在for循环中保留某种计数器。 当该计数器达到4时,您应该重置它并相应地更改正在发生的事情。 冲洗并重复。 我已经留给您一些更详细的实现细节,因为很难确切说明您的工作方式和管理方式。

int counter = 0;
for (Integer arrayitem : array) 
    {
            counter++;
            assign to table;
            if (counter == 4)
            {
                change what table we are now assigning to;
                counter = 0;
            }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM