English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Java Exception Handling

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序来打印数组

Java comprehensive examples

在此程序中,您将学习不同的技术来用Java打印给定数组的元素。

Example1:使用For循环打印数组

public class Array {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        for (int element : array) {
            System.out.println(element);
        }
    }
}

When the program is run, the output is:

1
2
3
4
5

在上述程序中,for-each循环用于迭代给定数组array。

它访问中的每个元素,并使用println()进行数组打印。

Example2:使用标准库数组打印数组

import java.util.Arrays;
public class Array {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        System.out.println(Arrays.toString(array));
    }
}

When the program is run, the output is:

[1, 2, 3, 4, 5]

Dans le programme ci-dessus, la boucle for a été remplacée par une ligne de code avec la fonction Arrays.toString().

As you can see, this provides clean output without any additional code lines.

Example3:print multidimensional array

import java.util.Arrays;
public class Array {
    public static void main(String[] args) {
        int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}};
        System.out.println(Arrays.deepToString(array));
    }
}

When the program is run, the output is:

[[1, 2], [3, 4], [5, 6, 7]]

In the above program, since each element of the array contains another array, only Arrays.toString() is used to print the address of the elements (nested arrays).

To get numbers from the internal array, we only need another function Arrays.deepToString(). This gives us the numbers1,2and so on, we are looking for.

This function also applies to3多维数组。

Java comprehensive examples