您的位置:首页 > 编程语言 > Java开发

JAVA流程控制与函数

2018-01-02 17:59 281 查看

Break;

跳出语句 后面代码永远不会执行

代码示例:

//打印[0, 100]中是7的倍数中的值最大那个数
public class Demo02 {
public static void main(String[] args) {
System.out.println(max);
for (int i = 100; i >=0; i--) {
if (i%7 ==0) {
max =i;
break;
}
}System.out.println(max);
}
}
输出 98


continue;

结束本次循环,继续下一次循环

代码示例:

// 一共有十个数,不打印3  5  9
public class Demo03 {
public static void main(String[] args) {
for (int i = 1; i <= 12; i++) {
if (i==3 || i ==5 || i == 9) {
continue;
}
System.out.println(i);
}
}
}


Math 函数

随机数方法返回的是[0,1) double值 伪随机数(按照规则随机)


代码示例:

//随机生成20个数,并输出最大数
public class Demo04 {
public static void main(String[] args) {
int max = 0,i=0;
for ( i = 0; i < 20; i++) {
int b = (int) (Math.random()*291+10);
if (max<b) {
max =b;
}System.out.println(b);
}   System.out.println("最大数为"+max);
}
}


函数

函数:封装了特定功能的代码块

函数好处: 方便使用 减少你重复代码书写

函数的写法:

关键字  返回值类型  函数名
public void     fun     (参数类型 参数1,参数类型 参数2,....){
//  函数中的语句1;
//  函数中的语句2;
//return后面返回的 返回值 要跟函数的返回值类型 对应
return 返回值;
}


函数的分类:

无参数无返回值函数

有参数有返回值函数

有参数无返回值函数

无参数有返回值函数

函数的调用:

使用 函数名(传入的参数);

编写函数的步骤:

确定函数有没有返回值 根据实际情况考虑是否在接下来的需要使用返回值

确定函数有没有参数 有的话 是几个 都是什么类型

有返回值的函数,不接收返回值也行

代码示例:

public class Demo05 {
public static void Print() {        //无参数无返回值函数
System.out.println("Hello World");
}

public static int count(int a,int b) {      //函数名字可以重复
int sum = 0;
sum =a+b;
return sum;
}

public static int count(int a,int b,int c) {
int sum = a+b+c;
return sum;
}

public static void main(String[] args) {
int sum =count(3,4,2);  //调用函数和接收函数
System.out.println(sum);

}
}


函数的重载:

实现相同的功能,但是函数的内部实现不同函数的重载是函数的名字相同 并且只跟参数有关 只跟参数有关(参数的类型 参数的顺序 参数的个数 有关) 跟参数的返回值,名字无关

代码示例:

// 计算两个数的最大值  计算三个数的最大值 计算四个数的最大值
public class Demo06 {
public static int maxnum(int a,int b) {
int max = ( a > b ) ? a : b;    //三目运算法
return max;

public static int maxnum(int a,int b,int c) {
int max = maxnum( a , b );
return max > c ? max : c;
}

public static int maxnum(int a,int b,int c,int d) {
int max =   maxnum( a , b, c);
return max > d ? max : d;
}

public static void main(String[] args) {
int sum = maxnum( 1, 5, 6, 7 );
System.out.println(sum);
}
}


递归函数:

调用一个和自己函数名相同的函数(自己调用自己)递归调用使用递归出口,否则相当于死循环.

代码示例:

public class Demo07 {
public static int fun(int x) {
if (x == 1) {               //递归出口
return 1;
}
return x*fun(--x);
}
public static void main(String[] args) {
int sum = fun(4);
System.out.println(sum);
}
}
输出 24
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: