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

前端 未结 13 1676
情书的邮戳
情书的邮戳 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:03

    In your example, j+=3 increments by 3.

    (Not much else to say here, if it's syntax related I'd suggest Googling first, but I'm new here so I could be wrong.)

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

    You can also write code as

    for(int i=0;i<n;i++)
    {
          //statements;
          i=i+2;//cause you want to increment i by 3 
    }
    
    0 讨论(0)
  • 2020-12-24 05:03
    for (let i = 0; i <= value; i+=n) { // increments by n
    /*code statement*/
    }
    

    this format works for me incrementing index by n

    for (let i = 0; i <= value; i+=4) { // increments by 4
    /*code statement*/
    }
    

    if n = 4 this it will increment by 4

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

    Simply try this

    for(int i=0; i<5; i=i+2){//value increased by 2
    //body
    }
    

    OR

    for(int i=0; i<5; i+=2){//value increased by 2
    //body
    }
    
    0 讨论(0)
  • 2020-12-24 05:09

    That’s because j+3 doesn’t change the value of j. You need to replace that with j = j + 3 or j += 3 so that the value of j is increased by 3:

    for (j = 0; j <= 90; j += 3) { }
    
    0 讨论(0)
  • 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.  
    
    0 讨论(0)
提交回复
热议问题