for嵌套循环讲解举例
时间: 2023-12-06 08:37:13 浏览: 81
在Java中,for循环嵌套可以用于多维数组的遍历,也可以用于打印图形等场景。以下是两个例子:
1. 遍历二维数组
```java
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8,9}};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j <[i].length; j++) {
.out.print(arr[i][j] + " ");
}
System.out.println();
}
```
输出:
```
1 2 3
4 5 6
7 8 9
```
2. 打印图形
```java
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
```
输出:
```
*
* *
* * *
* * * *
* * * * *
```
阅读全文