简体   繁体   English

每循环5次迭代增加一次int变量(JAVA)

[英]Increment int variable every 5 iterations of loop (JAVA)

i want to Increment int variable every 5 iterations of loop. 我想每循环5次递增int变量。 so the current int is 009. I want to change it to an infinite loop wherein the value add + 1 every 5 loops. 因此当前的int为009。我想将其更改为一个无限循环,其中值每5个循环加+ 1。 so after that the value of 009 will change to 010, then after 5 loops. 因此之后009的值将更改为010,然后经过5次循环。 again it will change into 011. 再次将其更改为011。

 String itemID = "2014-009";
    for (int i = 0; i <= 5; i++) {
        String sdf = new SimpleDateFormat("yyyy").format(new java.util.Date());
        String[] parts = itemID.split("-");
        String part2 = parts[1];
        int result = Integer.parseInt(part2);
        String second = sdf + "-" + String.format("%03d", result + 1);
        JOptionPane.showMessageDialog(null, second);
        System.out.println(second);
    }

Something like this should work: 这样的事情应该起作用:

int value = 0;
for (int i = 0; ; i++) {
    if (i%5 == 0) {
        value++;
    }
}

Explanation: 说明:

  • The loop has no end, because it doesn't have a condition 循环没有结束,因为它没有条件
  • The value variable is incremented only every 5 iterations value变量仅每5次迭代增加一次
  • We enforce that restriction by asking whether i is exactly divided by 5 我们通过询问i是否被5精确除以实施该限制

Be aware that I'm not taking into account the fact that int s are finite and at some point they will overflow. 请注意,我没有考虑到int有限的,并且在某些时候它们会溢出的事实。 For truly "infinite" values (limited only by the memory available in your machine), we would have to use arbitrary precision values, BigInteger will come in handy for that. 对于真正的“无限”值(仅受计算机可用内存限制),我们将不得不使用任意精度值, BigInteger将非常有用。

Well, you should initialize result outside the loop. 好了,您应该在循环之外初始化结果。 Then you can do an infinite loop with a counter that checks if the iteration is divisable by 5 : 然后,您可以使用一个计数器进行无限循环,该计数器检查迭代次数是否可以除以5:

....
int result = Integer.parseInt(part2);
int i = 0;

while (true) {
    i++;
    if (i%5 == 0)
        result++;
    ....
}
for(float i=0; i<10; i=i+0.2f){
     System.out.println((int) i);
}

You can adapt the rest 你可以适应其余的

In my case all above works on first iteration because 0%5 == 0 in my case is true and I suggest to write code like this: 在我的情况下,所有上述操作均适用于第一次迭代,因为在我的情况下0%5 == 0是正确的,我建议编写如下代码:

if(i%5 == 0 && i != 0) {//6 threads per one operation
   lq1.join();
   lq2.join();
}

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

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