How to print the values of an array in Java?
In Java, you can loop through an array using a for loop and print the values of the array using the System.out.println() method.
Here is a common method:
public class PrintArray {
public static void main(String[] args) {
// 定义一个整型数组
int[] numbers = {1, 2, 3, 4, 5};
// 使用for循环遍历数组并打印每个元素的值
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
Output results:
1
2
3
4
5
Another method is to use an enhanced for loop (also known as a for-each loop).
public class PrintArray {
public static void main(String[] args) {
// 定义一个整型数组
int[] numbers = {1, 2, 3, 4, 5};
// 使用增强的for循环遍历数组并打印每个元素的值
for (int number : numbers) {
System.out.println(number);
}
}
}
The output is the same as the method mentioned above.