for循环的初始意义是遍历一串具有相同特性的值
1、遍历数组,根据索引去求值
点击查看代码
public class ForDemo1 {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7};
for (int i = 0; i < arr.length; i++) {
System.out.println("arr["+i+"] = "+arr[i]);
}
}
}
for循环的嵌套(双重for循环)
遍历数组
点击查看代码
public class ForDemo2 {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print("arr["+i+"] = "+arr[i]+"\t\t"); //i 不走内层循环所以一直不变
System.out.println("arr["+j+"] = "+arr[j]);// j走外层循环,值J++
}
System.out.println();//内层for循环结束了,保留一行
}
}
}
for循环的嵌套(双重for循环),j从i开始
规律:跟自己及一会的数组进行比较,带最后一个
点击查看代码
public class ForDemo3 {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length ; j++) { //外层i与内层i有关(次数保持一致)
System.out.print( "i :" +"arr["+i+"] = "+arr[i]+"\t\t");
System.out.println("j :"+"arr["+j+"] = "+arr[j]);
}
System.out.println();
}
}
}
for循环的嵌套(双重for循环),j的长度限定为length - 1
点击查看代码
package com.shujia.demotest;
public class ForDemo4 {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - i ; j++) { //外层i与内层i有关(次数保持一致)
System.out.print( "i :" +"arr["+i+"] = "+arr[i]+"\t\t");
System.out.println("j :"+"arr["+j+"] = "+arr[j]);
}
System.out.println();
}
}
}
每个数只跟自己后面的数进行比较
点击查看代码
public class ForDemo3 {
public static void main(String[] args) {
int[] arr = {1,2,3,4};
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length ; j++) { //外层i与内层i有关(次数保持一致)
System.out.print( "i :" +"arr["+i+"] = "+arr[i]+"\t\t");
System.out.println("j :"+"arr["+j+"] = "+arr[j]);
}
System.out.println();
}
}
}