1、for循环遍历数组
用for循环遍历数组是很常见的一种方法,Java语言中通过数组的length属性可获得数组的长度。
package demo;
public class test {
public static void main(String[] args) {
int [] array = {1,2,3,4,5};
for(int i = 0;i < array.length;i++) {
System.out.print(array[i] + " ");
}
}
}
2、基于循环语句的遍历
JDK1.5对for语句的功能给予扩充、增强,以便于更好的遍历数组;
语法格式:
for(声明循环变量:数组的名字){
....
}
例子:
package demo;
public class test {
public static void main(String[] args) {
int [] array = {1,2,3,4,5};
for(int in:array) {
System.out.print(in + " ");
}
}
}
3、使用toString()方法遍历数组
这种方法是JDK1.5提供的一个简单的输出数组元素的值的方法。使用Arrays类调用public static String toString(int[] a)方法可以得到指定的一维数组a的如下格式的字符串表示。
[a[0],a[1]…a[a.lenth-1]]
package demo;
import java.util.Arrays;
public class test {
public static void main(String[] args) {
int [] array = {1,2,3,4,5};
System.out.print(Arrays.toString(array));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)