简体   繁体   中英

Java loops how to make incremental with jump?

Trying to make a loop in java that goes like this

1
2
3
4
5
1000
1010
1020
1030
1040

Right now my code is

 for(int j = 1; j <=5; j += 1){
     for(int i = 1000; i <=1040; i += 10){
         System.out.println(+ j );
         System.out.println(+ i );
     }
 }

And this is not working at all as its printing every number 5 times.

Two separate loops since there is no relation between first 5 and last 5 numbers.

for(int j = 1; j <=5; j += 1) {
    System.out.println(j);
}

for(int i = 1000; i <=1040; i += 10){
    System.out.println(i);
}

Please try this. If your purpose is to only display the number like above. Then you can do that with one for statement.

public class HelloWorld
{
  public static void main(String[] args)
  {
    for(int j = 1; j <=5; j += 1){
      System.out.println(j);
    }
    for(int i = 1000; i <=1040; i += 10){
        System.out.println(i);
    }
  }
}

Or if you really really really want to do it in one loop:

int i=1;
while(i<=1040)
{
   System.out.println(i);
   if(i<5){i++; continue;}
   else if(i==5){i=1000; continue;}
   else i+=10; 
}

Output:

1
2
3
4
5
1000
1010
1020
1030
1040

Otherwise just use 2 for loops (the first with +1 increment, the second with +10 increments) in sequence and not nested.

for(int j=1; j<=5; j++) {
    System.out.println(j);
}

for(int j=1000; j<=1040; j+=10){
    System.out.println(j);
}

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