1、循环变量的声明和初始化
2、循环条件
3、循环体
4、循环变量的更新
1、是否存在重复性操作
2、如果存在,确定四要素
3、选择循环结构,套用其语法
1.while(条件){循环体}
2.do{循环体}while(条件);
3.for(循环变量的声明和初始化;循环变量的更新;){循环体}
循环跳转语句: continue; 结束本次循环,进入下一次循环
break; 结束循环
for(声明语句 : 表达式) { //代码句子 }
下面举例演示:
说一百遍我爱祖国,分析这个循环的四要素
a.循环条件的声明和初始化
byte count = 1; //从第一遍开始
b.循环条件
count <= 100; //到100遍结束
c.循环体
System.out.print(“第”+count+“次:我爱你”); //每次循环输出
d.循环变量更新
count++; //判断次数
for循环
public class Practice { public static void main(String[] args){ //说一百遍我爱祖国 byte count = 1; for(count = 1;count <= 100;count++){ System.out.println("第"+count+"次:我爱祖国"); } } }while循环
public class Practice { public static void main(String[] args){ //说一百遍我爱祖国 while (count <= 100){ System.out.println("第"+count+"次:我爱祖国"); count++; } } }do while循环
public class Practice { public static void main(String[] args){ //说一百遍我爱祖国 byte count = 1; do{ System.out.println("第"+count+"次:我爱祖国"); count++; }while(count <= 100); } }continue(让程序立刻跳转到下一次循环的迭代)
public class Practice { public static void main(String[] args){ //说一百遍我爱祖国 byte count = 1; for(count = 1;count <= 100;count++){ if(count<100){continue;} System.out.println("第"+count+"次:我爱祖国"); } } } //输出结果为: 第100次:我爱祖国break(主要用在循环语句或者 switch 语句中,用来跳出整个语句块)
public class Practice { public static void main(String[] args){ //说一百遍我爱祖国 byte count = 1; for(count = 1;count <= 100;count++){ if(count>2){break;} System.out.println("第"+count+"次:我爱祖国"); } } } //输出结果为: 第1次:我爱祖国 第2次:我爱祖国如果说变量是一组存储空间的表示,那么数组就是一组类型相同的连续的存储空间的表示
优点:1、类型相同:不同考虑类型 2、连续:遍历
缺点:1、类型相同:无法解决不同类型多个值的存储 2、连续:插入,移除
a.声明 xxx() array;
b.★分配空间 array = new xxx[int LENGTH];
c.赋值 array[int INDEX] = value;
d.使用 System.out.println(array[int INDEX])
1、不可变
2、长度:int len = array.length;
3、下标(索引):0~array,length-1 如果超过范围会报异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1a+b+c用法 xxx[] array = {VALUE1,VALUE2,…};
eg:int[] arr={};
int[] arr2={5,7,9};
int[] arr3=new int[]{5,7,9};
下面举例演示:
import java.util.Random; public class Practice { public static void main(String[] args){ //判断一个随机数是否存在数组中 Random rand = new Random(); int[] arr = {3,7,13,18,19,21,24,26,29,31,32,38,41,44,45,47,50}; int v = rand.nextInt(50) + 1; System.out.print(v+"\t"); int count=0; for (int i = 0; i < arr.length-1; i++) { if(v==arr[i]){ count=i; break; }else{ count++; } }if(count==16){ System.out.print(v+"这个不存在于这个数组中"); }else{ System.out.print(count); } } } //输出结果为: 随机数为26 26这个数存在于这个数组中原创作者:wsjslient
作者主页:https://blog.csdn.net/wsjslient
参考文档:https://www.runoob.com/java/java-tutorial.html