[英]Java loops how to make incremental with jump?
Trying to make a loop in java that goes like this 试图在Java中进行这样的循环
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. 这根本不起作用,因为它每打印5次。
Two separate loops since there is no relation between first 5 and last 5 numbers. 由于前5个数字和后5个数字之间没有关系,因此有两个单独的循环。
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.
然后,您可以使用一个for语句来做到这一点。
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. 否则,只需按顺序使用2 for循环(第一个循环以+1递增,第二个循环以+10递增)且不嵌套。
for(int j=1; j<=5; j++) {
System.out.println(j);
}
for(int j=1000; j<=1040; j+=10){
System.out.println(j);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.