How to make for loops in Java increase by increments other than 1

前端 未结 13 1675
情书的邮戳
情书的邮戳 2020-12-24 04:33

If you have a for loop like this:

for(j = 0; j<=90; j++){}

It works fine. But when you have a for loop like this:

for(j          


        
相关标签:
13条回答
  • 2020-12-24 04:47

    The "increment" portion of a loop statement has to change the value of the index variable to have any effect. The longhand form of "++j" is "j = j + 1". So, as other answers have said, the correct form of your increment is "j = j + 3", which doesn't have as terse a shorthand as incrementing by one. "j + 3", as you know by now, doesn't actually change j; it's an expression whose evaluation has no effect.

    0 讨论(0)
  • 2020-12-24 04:51

    It should be like this

    for(int j = 0; j<=90; j += 3) 
    

    but watch out for

    for(int j = 0; j<=90; j =+ 3) 
    

    or

    for(int j = 0; j<=90; j = j + 3)
    
    0 讨论(0)
  • 2020-12-24 04:57
    for(j = 0; j<=90; j = j+3)
    {
    
    }
    

    j+3 will not assign the new value to j, add j=j+3 will assign the new value to j and the loop will move up by 3.

    j++ is like saying j = j+1, so in that case your assigning the new value to j just like the one above.

    0 讨论(0)
  • 2020-12-24 04:58

    It's just a syntax error. You just have to replace j+3 by j=j+3 or j+=3.

    0 讨论(0)
  • 2020-12-24 05:00

    Change

    for(j = 0; j<=90; j+3)
    

    to

    for(j = 0; j<=90; j=j+3)
    
    0 讨论(0)
  • 2020-12-24 05:02

    If you have a for loop like this:

    for(j = 0; j<=90; j++){}
    

    In this loop you are using shorthand provided by java language which means a postfix operator(use-then-change) which is equivalent to j=j+1 , so the changed value is initialized and used for next operation.

    for(j = 0; j<=90; j+3){}
    

    In this loop you are just increment your value by 3 but not initializing it back to j variable, so the value of j remains changed.

    0 讨论(0)
提交回复
热议问题