一 循环的种类:
- while
结构:
int n = 1; while(true) { System.out.println("我是谁 我从哪里来"); //添加一个出口停止循环 if (n==5) { //接收循环 跳出循环语句 break; // break 后面的语句是永久不会执行. } n++; }
如果判断条件为true 则 while 成为死循环 可以在循环体中添加个出口(if判断)来结束循环
- do while
do { //代码语句 }while(判断表达式);
do while 是先执行循环语句 再进行条件判断.
- for 循环
for(初始值定义1; 判断表达式2; 自增或自减3) { //代码语句4 }
执行顺序 1--2--4--3--2---4--3 .......
for 循环中的变量只能在循环中使用.
二 循环的应用
明确循环停止条件时一般使用while循环 遍历数组是使用for循环;
循环套循环
for (int i = 0; i < 5; i++) { for (int j=i;j<5;j++) { System.out.print("*"); } System.out.println(); }
for (int i = 0; i < 5; i++) { for (int j = 0; j < 2*i+1; j++) { System.out.print("*"); } System.out.println(); }
通过以上两个示例我们可以得到一个结论:
尖角向上的三角形 修改内循环 判断值部分
尖角向下的三角形 修改内循环 初始值部分
break 和continue在for循环中的使用
for (int i = 0; i < 10; i++) { for (int j = 0; j <10; j++) { if (j==3) { //break; //结束当前循环 外循环继续执行 continue ; //跳出当前循环 下一次循环继续执行,不影响外循环 } System.out.print(j); } System.out.println(); } }break 和 continue 都只是对最近的循环产生影响而不影响上层循环.
break
012 012 012 012 012 012 012 012 012 012continue
012456789 012456789 012456789 012456789 012456789 012456789 012456789 012456789 012456789 012456789
三 随机数
随机数 使用(Math类)
double random = Math.random()
伪随机:通过系统一个计算规则算出随机数
返回的随机数范围[0,1)
得出随机范围为[min,max]的随机数
int random= (int)(Math.random()*(max+1-min)+min);四 函数
函数:分装特定功能的代码串. 好处:减少重复代码 提高了开发效率 写法: 没有返回值使用 void 函数的书写位置 必须在类中 不能在函数中定义函数; 函数调用必须在主函数中. 参数列表 关键字 (public static)+返回值类型 +函数名(小驼峰) + (参数类型1 参数名1,参数类型2 参数名2........)+{ 函数体:执行的特定功能的语句 return + 返回值; }
函数传参和重载
传参可以提高方法的拓展性
函数的返回值可以不用接收
函数的重载 :
实现相同功能 但是内部实现不同 就可以使用函数的重载;
是不是函数的重载只跟 参数有关 并且 只跟参数的类型 参数顺序 参数个数 有关,同 函数的返回值类型 函数的实现无关.
是否重载只更参数有关 当参数类型 顺序 个数不同是 可以重载 ;
应用:
public static void main(String[] args) { int tt=max(4, 5 , 8 ,66 ,88); System.out.println(tt); } /** * * 需求: 定义函数 * 1.计算2个数的最大值 * 2.计算3个数的最大值 * 3.计算4个数的最大值 * 4.计算5个数的最大值 */ public static int max(int a, int b) { int num=(a>b)?a:b; return num; } public static int max(int a, int b, int c) { int num = max(a, b); return (num>c)?num:c; } public static int max(int a, int b, int c,int d) { int num = max(a, b, c); return (num>d)?num:d; } public static int max(int a, int b, int c,int d,int e) { int num = max(a, b, c, e); return (num>e)?num:e; }
五 递归函数
//编写 4! public static double fun(long n) { //4*3*2*1 传进来的值自减; if (n == 1) { return 1; } return n * fun(n - 1); } public static void main(String[] args) { double num = fun(100); System.out.println(num); /*int mul = 1; for (int i = 1; i <= 4; i++) { mul*=i; } System.out.println(mul);*/ }
递归函数:
方法中出现调用同名函数 函数中必须有分支:
要求输出一个序列:1,1,2,3,5,8,11......(每一个数为前两个数子之和,要求用递归函数) 用java递归来表示一个函数:F(n)=F(n-1)+F(n-2);F(0)=1;F(1)=1; 分析:X1=1; X2=1; X3=X1+X2; X4=X2+X3; ... ; Xn=X(n-1)+X(n-2) public int F(int n){ if(n==1){ return 1; }else if(n==2){ return 1; }else{ return F(n-1)+F(n-2); } }