Java程序打印数组元素
在Java中,数组是将相同类型的数据存储在一起的常用方式。存储的项目或值称为数组的元素。在本文中,我们将学习如何创建数组并打印其元素。
在Java中打印数组元素
使用以下方法来打印数组的元素:
- 使用for循环
- 使用while循环
- 使用Arrays.toString()方法
使用For循环打印数组元素
当我们知道需要重复执行任务多少次时,使用for循环。在这种情况下,数组的长度是已知的,因此,我们使用for循环并逐个打印数组元素。
示例
在下面的示例中,我们使用for循环来打印给定数组的元素。
public class newarr_class {
public static void main(String[] args) {
// creating simple array
int [] array1 = {11, 22, 32, 42, -52};
// creating 2D array
int [][] array2 = {{11, 222}, {23, 42}, {-25, 26}, {-27, 28}};
//printing individual elements of 1D array
System.out.println("\nThe elements in the 1D int array are:\n");
for (int n = 0; n < array1.length; n++){
System.out.println(array1[n]);
}
//printing all elements of 2D array
System.out.println("\nThe 2D Int array is:\n ");
for (int n = 0; n < array2.length; n++) {
for (int m = 0; m < array2[n].length; m++) {
System.out.print(array2[n][m] + " ");
}
System.out.println();
}
}
}
执行代码后,将打印以下结果:
The elements in the 1D int array are: 11 22 32 42 -52 The 2D Int array is: 11 222 23 42 -25 26 -27 28
使用While循环打印数组元素
只要给定条件为真,while循环就会重复执行代码块。在这里,我们将循环运行到数组长度并打印其元素。
示例
以下示例显示了如何使用while循环来打印数组元素。
public class newarr_class {
public static void main(String[] args) {
// Creating a simple 1D array
int[] array1 = {11, 22, 32, 42, -52};
// Printing individual elements of the 1D array using a while loop
System.out.print("\nThe elements in the 1D int array are:\n");
int n = 0;
while (n < array1.length) {
System.out.println(array1[n]);
n++;
}
}
}
以上代码将生成以下结果:
The elements in the 1D int array are: 11 22 32 42 -52
使用Arrays.toString()打印数组元素
Arrays.toString()方法返回数组元素的字符串表示形式。
示例
在此示例中,我们将使用Arrays.toString()方法来打印数组元素。
import java.util.Arrays;
public class newarr_class {
public static void main(String[] args) {
String[] strarray = new String[]{"One", "Two", "Three", "Four", "Five"};
// use of Arrays.toString()
System.out.println(Arrays.toString(strarray));
}
}
运行此代码后,将显示以下输出:
[One, Two, Three, Four, Five]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP