简体   繁体   中英

Increment int variable every 5 iterations of loop (JAVA)

i want to Increment int variable every 5 iterations of loop. so the current int is 009. I want to change it to an infinite loop wherein the value add + 1 every 5 loops. so after that the value of 009 will change to 010, then after 5 loops. again it will change into 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
  • We enforce that restriction by asking whether i is exactly divided by 5

Be aware that I'm not taking into account the fact that int s are finite and at some point they will overflow. 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.

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 :

....
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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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