[英]How to produce odd numbers using only a for loop
I must produce the following output using only nested for loops: 我必须只使用嵌套的for循环生成以下输出:
-----1----- ----- ----- 1
----333---- ---- ---- 333
---55555--- --- 55555 ---
--7777777-- --7777777--
-999999999- -999999999-
I cannot use any while or if statements 我不能使用任何while或if语句
Here is my code: 这是我的代码:
public static void printDesign() {
//for loop for the number of lines
for (int i = 1; i <= 9; i++) {
//for loop for the left -
for (int j = 1; j <= 6 - i; j++) {
System.out.print("-");
}
//for loop for #'s
for (int k = 1; k <= 2 * i - 1; k++) {
System.out.print(i);
}
//for loop for the right -
for (int x = 1; x <= 6 - i; x++) {
System.out.print("-");
}
System.out.println();
}
}
This is what it produces: 这就是它产生的:
-----1----- ----- ----- 1
----222---- ---- ---- 222
---33333--- --- 33333 ---
--4444444-- --4444444--
-555555555- -555555555-
66666666666 66666666666
7777777777777 7777777777777
888888888888888 888888888888888
99999999999999999 99999999999999999
How can I get it to only produce the odd numbers? 我怎样才能得到它只产生奇数?
Your solution is very close to the correct one. 您的解决方案非常接近正确的解决方案。 Simply change the step of
i
in the outer cycle. 只需在外循环中更改
i
的步骤即可。
for (int i = 1; i <= 9; i += 2) {
for (int j = 0; j < (9 - i) / 2; j++) System.out.print('-');
for (int k = 0; k < i; k++) System.out.print(i);
for (int l = 0; l < (9 - i) / 2; l++) System.out.print('-');
System.out.println();
}
Output: 输出:
----1----
---333---
--55555--
-7777777-
999999999
Change your first for-loop increment value from 1 to 2. 将您的第一个for循环增量值从1更改为2。
for (int i = 1; i <= 9; i+=2){}
for(int i = 1; i <= 9; i + = 2){}
Sounds like a homework assignment. 听起来像是家庭作业。 But I'll give you the hint that the key is in the "for(" line.
但我会给你一个提示,关键是在“for(”行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.