JAVA中用加强遍历数组
时间: 2023-07-13 11:28:20 浏览: 63
在Java中,可以使用加强的for循环语法来遍历数组。该语法使用冒号来遍历数组,示例如下:
```java
int[] arr = {1, 2, 3, 4, 5};
// 遍历数组
for (int num : arr) {
System.out.println(num);
}
```
输出结果为:
```
1
2
3
4
5
```
在上述示例中,变量`num`会依次代表数组`arr`中的每个元素,方便我们进行处理。
相关问题
Java中用list存储数组的示例
下面是一个Java中用List存储数组的示例:
```java
import java.util.ArrayList;
import java.util.List;
public class ListArrayExample {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
List<Integer> list = new ArrayList<>();
for (int i : array) {
list.add(i);
}
System.out.println("List containing array elements: " + list);
}
}
```
在这个示例中,我们首先定义了一个整数类型的数组 `array`,然后创建了一个空的 `ArrayList`,名为 `list`。接下来,我们使用 `for` 循环遍历数组中的每个元素,并将其添加到 `list` 中。最后,我们打印出存储在 `list` 中的元素。
输出结果应该为:
```
List containing array elements: [1, 2, 3, 4, 5]
```
下面的代码所要实现的功能是:数学中的矩阵在java中用二维数组来实现,程序实现两个
在Java中,可以使用二维数组来实现数学中的矩阵。下面的代码是实现两个矩阵相加的功能:
```java
public class MatrixAddition {
public static void main(String[] args) {
int[][] matrix1 = {{1, 2}, {3, 4}};
int[][] matrix2 = {{5, 6}, {7, 8}};
int[][] result = new int[matrix1.length][matrix1[0].length];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("Matrix 1:");
printMatrix(matrix1);
System.out.println("Matrix 2:");
printMatrix(matrix2);
System.out.println("Result of matrix addition:");
printMatrix(result);
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
System.out.println();
}
}
```
以上代码通过定义两个二维数组matrix1和matrix2来代表两个矩阵,然后通过双重for循环遍历每个元素,将对应位置的元素相加并存储到result数组中。最后打印出原始矩阵和相加后的矩阵。
这段代码实现了两个矩阵相加的功能,是Java中二维数组操作的一个示例。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)