要显示数组中的所有元素,可以使用循环遍历数组并打印每个元素。以下是一个示例代码:
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
// 使用for循环遍历数组并打印每个元素
System.out.println("使用for循环遍历数组并打印每个元素:");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// 使用for-each循环遍历数组并打印每个元素
System.out.println("使用for-each循环遍历数组并打印每个元素:");
for (int num : arr) {
System.out.println(num);
}
}
}
运行上述代码,将会输出:
使用for循环遍历数组并打印每个元素:
1
2
3
4
5
使用for-each循环遍历数组并打印每个元素:
1
2
3
4
5
通过使用循环遍历数组,可以依次访问数组中的每个元素并进行相应的操作,比如打印、计算等。