简体   繁体   English

用Java生成序列号

[英]Generating sequence numbers in Java

I would like to generate sequence number from 01 to 10. But I only want the odd ones. 我想生成从01到10的序列号。但是我只想要奇数。 For example, 例如,

01 03 05 07 09 01 03 05 07 09

I tried this way. 我尝试过这种方式。

for (int i = 1; i < 10; i++) {
    String sequence = String.format("%02d", i);
    System.out.println(sequence); //this prints out from 01,02,03.... to 09.

So how should I change my code to omit the even ones in between? 那么,如何更改代码以省略两者之间的偶数呢?

Since you want it formatted, only with odd numbers, this outputs: 由于您希望将其格式化为仅具有奇数的格式,因此将输出:

01 03 05 07 09 01 03 05 07 09

for (int i = 1; i < 10; i+=2)
  System.out.println( String.format("%02d", i) );

Use a for loop changing the increment stage: 使用for循环更改增量阶段:

for (int i = 1; i < 10; i += 2)
    System.out.println(i);

You can just make the loop increment by 2 instead of by just 1! 您可以使循环增加2而不是仅增加1!

Example with your code: 您的代码示例:

for (int i = 1; i < 10; i+=2) 
{
    String sequence = String.format("%02d", i);
    System.out.println(sequence);
}

just use a loop 只是使用一个循环

For loop 对于循环

for(int i=1;i<=10;i+=2)
System.out.println(i);

While loop While循环

int i=1;
while(i<=10){
System.out.println(i);
i+=2;
}

Do-While loop 做循环

int i=1;
do{
System.out.println(i);
i+=2}while(i<=10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM