循环遍历数组方法总结
1 while循环语句
while(条件表达式){
执行语句
}
2 do…while循环语句
do{
执行语句
}while(条件表达式);
while和do...while区别:
while是先判断条件是否成立再执行循环体
do...while是先执行一次循环再判断条件是否成立
do..while循环体中至少被执行一次
3 for循环语句
for(初始化表达式 ;循环条件表达式 ; 循环后操作表达式){
语句序列
}
4 foreach循环语句
for(元素变量x : 遍历对象obj){
引用了x的Java语句;
}
5 举例一:3中方法
public class Circle {
public static void main(String[] args) {
String[] arr = new String[]{"张三","李四","小红","小李","校长","狗儿","花儿","莲儿","荡儿","华儿","赢儿"};
int index = 0;//索引变量
System.out.println("数组元素第一种方法:");
while(index<arr.length){ //while循环遍历数组
System.out.print(arr[index++]+" ");
}
System.out.println();
System.out.println("数组元素第二种方法:");
for(String x : arr){ //foreach循环遍历数组
System.out.print(x+" ");
}
System.out.println();
System.out.println("数组元素第三种方法:");
for(int a = 0; a < arr.length; a++){ //for循环遍历数组
System.out.print(arr[a]+" ");
}
}
}
6 举例二:九九乘法表
public class MultiplicationTable {
public static void main(String[] args) {
for(int i = 1; i <= 9; i++){
for(int j = 1; j<= i; j++){
System.out.print(j+"*"+i+"="+i*j+"\t");
}
System.out.println();
}
}
}