今晚我为 AP 计算机科学类(class)布置的简短作业是更改此嵌套循环,使其打印 1, 3, 5, 7 颗星,而不是 1, 2, 3, 4, 5, 6, 7 颗星。
这是我的代码:
public static void main(String args[])
{
//print 1,3,5,7 stars
for(int i=1; i<=7; i++)
{
for(int j=1; j<=i; j++)
{
System.out.print("*");
}
System.out.println();
}
}
最佳答案
将i
增加二而不是一
for(int i=1; i<=7; i = i + 2)
或按照@andreas的建议
for(int i=1; i<=7; i+= 2)
输出
*
***
*****
*******
编辑
根据 @andreas 下面的评论,在 java11+ 中,以下内容也是可能的
for(int i=1; i<=7; i += 2)
System.out.println("*".repeat(i));
关于java - 我将如何改变这个嵌套循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58423826/