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

前端 未结 13 1759
情书的邮戳
情书的邮戳 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 05:12

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

    j++ means j=j+1, j value already 0 now we are adding 1 so now the sum value of j+1 became 1, finally we are overriding the j value(0) with the sum value(1) so here we are overriding the j value by j+1. So each iteration j value will be incremented by 1.

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

    Here j+3 means j value already 0 now we are adding 3 so now the sum value of j+3 became 3 but we are not overriding the existing j value. So that JVM asking the programmer, you are calculating the new value but where you are assigning that value to a variable(i.e j). That's why we are getting the compile-time error " invalid AssignmentOperator ".

    If we want to increment j value by 3 then we can use any one of the following way.

     for (int j=0; j<=90; j+=3)  --> here each iteration j value will be incremented by 3.
     for (int j=0; j<=90; j=j+3) --> here each iteration j value will be incremented by 3.  
    

提交回复
热议问题