gpt4 book ai didi

java - 使用嵌套 for 循环的简单 Java 金字塔

转载 作者:太空宇宙 更新时间:2023-11-04 07:22:25 28 4
gpt4 key购买 nike

我在尝试找出一种使用用户输入创建金字塔的方法时遇到了很大的麻烦。它应该是这样的。

Enter a number between 1 and 9: 4
O
O
O
O
OOOO
OOOO
OOOO
OOOO
O
OO
OOO
OOOO

这就是我目前所拥有的

public static void main(String[] args) {
int number;
Scanner keyboard = new Scanner(System.in);

System.out.print("Enter a number between 1 and 9: ");
number = keyboard.nextInt();

for (int i = 1; i < 10; i++){
for (int rows = number; number < i; rows++){
System.out.print("O");
}
System.out.println();
}
}

我完全理解我想要完成的任务,但我不完全理解 for 循环是如何工作的。任何帮助将不胜感激,因为我完全迷失了!

最佳答案

基本上 for 循环的工作原理如下

// Take this example (and also try it)
for (int i = 0; i < 10; i++)
{
System.out.println(i);
}


// Explanation
for(int i = 0; // the value to start at - in this example 0
i < 10; // the looping conditions - in this example if i is less than 10 continue
// looping executing the code inclosed in the { }
// Once this condition is false, the loop will exit
i++) // the increment of each loop - in this exampleafter each execution of the
// code in the { } i is increments by one
{
System.out.println(i); // The code to execute
}

使用不同的起始值、条件和增量进行实验,尝试这些:

for (int i = 5; i < 10; i++){System.out.println(i);}
for (int i = 5; i > 0; i--){System.out.println(i);}

关于java - 使用嵌套 for 循环的简单 Java 金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19106399/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com