5、Java方法

1. 方法概述

  1. 方法:一种语法结构,可以把一段代码封装成一个功能,以便重复调用
  2. 方法的作用:提高代码复用性;程序逻辑更清晰

2. 方法定义、调用

注意:
a)方法定义:方法必须先创建
b)方法调用:方法创建后,需要手动使用后,才执行

2.1 格式

  1. 方法定义
修饰符 返回值类型 方法名 (形参列表[可以没有形参]) {
			方法体(需要执行的功能代码);
			return 返回值;[或无返回值,此时返回值类型为void]
}
// 示例:
//public static:修饰符   int:返回值类型  sum:方法名   int a, int b:形参列表
public static int sum(int a, int b){
    int c = a + b; //方法体
    return c; //c:返回值
}
  1. 方法调用
方法名(实际参数列表)
// 示例
sum(13, 10)

3. 方法使用常见问题

  1. 方法的编写顺序无所谓。
  2. 方法与方法之间是平级关系,不能嵌套定义。
  3. 方法的返回值类型为void (无返回值),方法内则不能使用return返回数据。
  4. 如果方法的返回值类型写了具体类型,方法内部则必须使用return返回对应类型的数据。
  5. return语句下面,不能编写代码,因为永远执行不到,属于无效的代码。
  6. 形参列表可以有多个,或没有;
  7. 如果有多个形参,形参之间用“,”隔开,且不能给初始化值。
  8. 方法不调用就不执行,调用时必须严格匹配方法的参数情况。
  9. 有返回值的方法调用时可以选择定义变量接收结果,或者直接输出调用,甚至直接调用;
  10. 无返回值方法的调用只能直接调用一下。

4. 方法案例

  1. 求和1~n
public static void main(String[] args) {
//方法调用
    int s1 = sum(100);
    int s2 = sum(50);
    System.out.println("s1:" + s1 + "   s2:" + s2); //s1:5050   s2:1275
}
// 方法定义
public static int sum(int n){
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}
  1. 判断奇数偶数
//方法调用
judge(2); //2:偶数
judge(5); //5:奇数
// 方法定义
public static void judge(int n){
    if (n % 2 == 1){
        System.out.println(n + ":奇数");
    } else{
        System.out.println(n + ":偶数");
    }
}
  1. 数组求最值
//方法调用
int[] arra = {41,61,55,15,67,48,49};
System.out.println(arrMax(arra));
// 方法定义
public static int arrMax(int[] a){
    int max = a[0];
    for (int i = 1; i < a.length; i++) {
        if (max < a[i]){
            max = a[i];
        }
    }
    return max;
}

5. 方法调用内存图

5.1 调用流程

  • 方法没有被调用时:在方法区中的字节码文件中存放
  • 方法被调用时:需要进入到栈内存中运行
  • 示例:
public static void main(String[] args) {
int sum = add(10, 20);
System.out.println(sum);
}
public static int add(int a, int b){
    int c = a + b;
    return c;
}

在这里插入图片描述

5.2 流程示例

  1. 代码
    public static void main(String[] args) {
        study();
    }

    public static void sleep(){
        System.out.println("sleep");
    }

    public static void eat(){
        System.out.println("eat");
    }

    public static void study(){
        System.out.println("eat");
        System.out.println("study");
        System.out.println("sleep");
    }
  1. 内存图
    在这里插入图片描述
    在这里插入图片描述

6.方法的参数传递案例

6.1 基本类型+引用类型 值传递

实参:调用方法时,实参列表中的参数。是方法外部定义的变量。
形参:定义方法时,形参列表中所声明的参数。

  1. 基本类型的值传递:在传输实参给方法的形参的时候,并不是传输实参变量本身,而是传输实参变量中存储的值,这就是值传递。
    不会改变数据值
public static void main(String[] args) {
    int a = 10;
    para(a);
    System.out.println("main:" + a);
}
public static void para(int a){
    System.out.println("para1:" + a);
    a = 20;
    System.out.println("para2:" + a);
}
/*
para1:10
para2:20
main:10
*/
  1. 引用类型的值传递:实参传递给形参的值为实参的地址。
    会改变数据值
int[] b = {12, 20, 23, 14};
para2(b);
System.out.println("main:" + b[0]);

public static void para2(int[] b){
    System.out.println("para1:" + b[0]);
    b[0] = 15;
    System.out.println("para2:" + b[0]);
}
/*
para1:12
para2:15
main:15
*/
  1. 基本类型和引用类型值
    1)都是值传递
    2)基本类型的参数:传输存储的数据值
    3)引用类型的参数:传输存储的地址值

6.2 参数传递案例

  1. 数组遍历
    需求:设计一个方法用于数组遍历,要求遍历的结果是在一行上的。
    例如:[11, 22, 33, 44, 55]
//方法调用
int[] arr = {11, 22, 33, 44, 55};
arrList(arr); //[11, 22, 33, 44, 55]
// 方法定义
    public static void arrList(int[] arr){
        if (arr != null & arr.length > 0){
            System.out.print('[');
            for (int i = 0; i < arr.length - 1; i++) {
                System.out.print(arr[i] + ", ");
            }
            System.out.println(arr[arr.length-1]+"]");
        }
    }
  1. 查找数组索引
    需求:设计一个方法可以接收整型数组,和要查询的元素值;最终要返回元素在该数组中的索引,如果数组中
    不存在该元素则返回-1。
    例如:[11, 22, 33, 44, 55] 输入元素44,返回素引3;输入元素88,返回-1。
    分析:
    1.定义方法,接收整型数组,查询的元素值,在方法体中完成元素查询的功能。—> 是否需要参数、返
    回值类型?
    2.定义数组,调用该方法,并指定要搜索的元素值,得到返回的结果输出。
//方法调用
int[] arr = {11, 22, 33, 44, 55};
System.out.println(arrIndex(arr,2)); //-1
//方法定义
public static int arrIndex(int[] a, int value){
    for (int i = 0; i < a.length; i++) {
        if (a[i] == value){
            return i;
        }
    }
    return -1;
}
  1. 比较2个数组是否-样
    需求:判断任意两个整型数组是否一样,并返回true或者false。(如果两个数组的类型,元素个数,元素顺序和内容是一样的我们就认为这2个数组是一模一样的。)
    例如:int[] arrs = {10, 20, 30}和int[] arrs = {10, 20, 30}:返回true
    分析:
    1.定义方法,接收2个整型数组,—> 是否需要参数、返回值类型?
    2.在方法内部完成判断的逻辑,并返回布尔结果。
//方法调用
int[] arr = {11, 22, 33, 44, 55};
int[] arr2 = {11, 22, 33, 44, 55};
System.out.println(arrSame(arr, arr2));  //true
//方法定义
public static boolean arrSame(int[] a, int[] b){
    if (a.length == b.length) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] != b[i]){
                return false;
            }
        }
        return true;
    }else {
        return false;
    }
}

7. 方法重载

7.1 概念

  1. 方法重载指同一个类中定义的多个方法之间的关系,满足下列条件的多个方法相互构成重载
    • 方法在同一个类
    • 方法名相同
    • 形参列表不同,类型、数量、顺序不同
// 方法调用
public static void main(String[] args) {
    fire();
    fire("japanese");
    fire("japanese",5);
}
// 方法定义
public static void fire(){
    System.out.println("japanese:1 fire");
    // 方法调用  调用其重载方法
    fire("japanese");
}
public static void fire(String location){
    System.out.println(location + ":" + "1 fire" );
    // 方法调用  调用其重载方法
    fire("japanese", 1);
}
public static void fire(String location, int num){
    System.out.println(location + ":" + num + " fire");
}
  1. 注意:

    • 重载仅对应方法的定义,与方法的调用无关,调用方式参照标准格式
    • 重载仅针对同一个类中方法的名称与参数进行识别,与返回值无关,换句话说不能通过返回值来判定两个方法是否相互构成重载
  2. 作用
    可读性好,方法名称相同提示是同一类型的功能,通过形参不同实现功能差异化的选择,这是一种专业的代码设计。

  3. 识别技巧

// 新方法
public static void open(){}
// 方法重载
public static void open(int i){}
// 方法重载
public static void open(int i, int j){}
// 方法重载
public static void open(double i, int j){}
// 方法重载
public static void open(int i, double j){}

// 与上面重复,不区分形参变量名
//public static void open(int a, double b){}

// 新方法 java区分大小写
public static void OPEN(){}

8. 补充:return关键字

  1. return可以用在任何方法中,跳出并结束当前方法的执行
public static void main(String[] args) {
    System.out.println("begin");
    //方法调用
    chu(2,0);
    System.out.println("end");
}
// 方法定义
public static void chu(int a, int b){
    if (b == 0){
        System.out.println("除数不能为0");
        return; //跳出并结束当前方法的执行
    }
    int c = a / b;
    System.out.println("the result is:" + c);
}
/*begin
除数不能为0
end*/

9 编程案例

9.1 买飞机票

  1. 需求:
    机票价格按照淡季旺季、头等舱和经济舱收费、输入机票原价、月份和头等舱或经济舱。
    机票最终优惠价格的计算方案如下:旺季(5-10月) 头等舱9折,经济舱8.5折,淡季(11月到来年4月)头
    等舱7折,经济舱6.5折。
  2. 分析:
    键盘录入机票的原价,仓位类型,月份信息,调用方法返回机票最终的优惠价格。
public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("please input the price of ticket:");
        float sale = sc.nextFloat();
        
        System.out.println("please input the month of ticket:");
        int month = sc.nextInt();
        System.out.println("please input the level of ticket(top:1  lower:2):");
        int level = sc.nextInt();
        System.out.println("the diacount price:" + price(sale, month, level));
}

    public static float price(float sale, int month, int level){
        if (month >= 5 && month <=10){
            switch (level){
                case 1:
                    sale *= 0.9;
                    break;
                case 2:
                    sale *= 0.85;
                    break;
                default:
                    System.out.println("the level has wrong");
                    return -1;
            }
        }
        else if (month == 11 || month == 12 || month >= 1 && month <=4){
            switch (level){
                case 1:
                    sale *= 0.7;
                    break;
                case 2:
                    sale *= 0.65;
                    break;
                default:
                    System.out.println("the level has wrong");
                    return -1;
            }
        }
        else{
            System.out.println("the month has wrong");
            return -1;
        }
        return sale;
    }
  1. 注意
    值匹配:switch
    区间匹配:if

9.2 找素数

  1. 需求
    判断101~200之间有多少素数,并输出所有素数。
    素数:除了1和他本身外,不能被其他正整数整除。
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 101; i <= 200; i++) {
            if (find(i) == 1){
                sum += 1;
            }
        }
        System.out.println('\n'+ "the sum of num is:" + sum);
    }

    //判断是不是素数
    public static int find(int a){
        // 标志:1素数 0非素数
        int flag = 1;
        for (int i = 2; i < Math.sqrt(a); i++) {
            if (a % i == 0){
                flag = 0;  //有其他因子,非素数
            }
        }
        // 素数输出值
        if (flag == 1){
            System.out.print(a + " ");
        }
        return flag;
    }

9.3 验证码

  1. 需求
    定义方法实现随机产生一个5位的验证码,每位可能是数字、大写字母、小写字母。
  2. 分析
    定义一个方法,生成验证码并返回:参数是位数,返回值类型string
    public static void main(String[] args) {
        String vai = Validnum(5);
        System.out.println("Random Vaild Code" + vai);
    }

    // 产生随机数验证码
    public static String Validnum(int len){
        // 返回字符串类型  字符串拼接‘ + ’
        String vaildStr = "";
        Random rd = new Random();
        for (int i = 0; i < len; i++) {
            // 随机生成数字/大写/小写字母
            int type = rd.nextInt(3);
            switch (type){
                case 0://大写字母(65--65+25)  强制类型转换
                    char ch = (char)(rd.nextInt(26)+65);
                    vaildStr += ch;
                    break;
                case 1://小写字母(97--97+25)   强制类型转换
                    char ch1 = (char)(rd.nextInt(26)+97);
                    vaildStr += ch1;
                    break;
                case 2:数字(0--9)
                    vaildStr += rd.nextInt(10);
                    break;
            }
        }
        return vaildStr;
    }
// NU4QK

9.4 数组元素的复制

  1. 需求
    把一个数组中的元素 复制到 另一个新数组中
  2. 分析
    动态初始化新数组,长度
    遍历原数组中的每个元素,依次赋值给新数组
    输出两个数组的内容
    public static void main(String[] args) {
        int[] a = {16, 54, 98};
        // 动态初始化数组
        int[] b = new int[a.length];
        copyArr(a, b);
        for (int i = 0; i < b.length; i++) {
            System.out.print(b[i] + " ");
        }
    }

    // 复制a数组元素到b数组  将两个数组作为形参,不需要返回值
    public static void copyArr(int[] a, int[] b) {
        for (int i = 0; i < a.length; i++) {
            b[i] = a[i];
        }
    }

9.5 评委打分

  1. 需求
    在唱歌比赛中,有6名评委给选手打分,分数范围是[0 - 100]之间的整数。选手的最后得分为:去掉最
    高分、最低分后的4个评委的平均分,请完成上述过程并计算出选手的得分。
  2. 分析
    把6个评委的分数录入到程序中去—>使用数组
    int[] scores = new int[6];
    遍历数组中每个数据,进行累加求和,并找出最高分、最低分。
    按照分数的计算规则算出平均分。
    public static void main(String[] args) {
        // 初始化分数数组
        int[] s_all = new int[6];
        score(s_all);
        max_min_avg(s_all);
    }

    // 获取全部得分 为分数数组复制
    public static void score(int[] s){
        Random rd = new Random();
        for (int i = 0; i < s.length; i++) {
            s[i] = rd.nextInt(101);
        }
        System.out.println("评委打分:");
        for (int i = 0; i < s.length; i++) {
            System.out.print(s[i] + " ");
        }
    }

    //找出数组最值, 去掉两值后求和求平均
    public static void max_min_avg(int[] a){
        // 初始设为数组的第一个值
        int max = 0;
        int min = 0;
        //求数组最大最小值的索引
        for (int i = 1; i < a.length; i++) {
            if (a[max] < a[i]){
                max = i;
            }
            if (a[min] > a[i]){
                min = i;
            }
        }
        //求去掉最大值,去掉最小值的所有和
        int sum = 0;
        System.out.println('\n'+"max:" +max + " min:" + min);
        for (int i = 0; i < a.length; i++){
            sum += a[i];
        }
        sum -= a[max];
        sum -= a[min];
        System.out.println("和为:" + sum);
        System.out.println("平均分:" + (sum * 1.0/a.length));
    }

9.6 数字加密

  1. 需求
    某系统的数字密码,采用加密的方式进行传输,规则如下:先得到每位数,然后每位数+5,再对10求余,最后将所有数字反转,得到一串新数字。

比如
----:1 9 8 3
+5:6 14 13 8
%10:6 4 3 8
反转:8 3 4 6

  1. 分析
    将每位数据存入数组中,遍历数组每位数据按照规则更改,将更改后的数据存入新数组中。
public class JiaMi {
    public static void main(String[] args) {
        int[] a = new int[4];
        ArrGenera(a);
        ChangeArr(a);
    }
    //生成数组,输出
    public static void ArrGenera(int[] a){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入密码:");
        for (int i = 0; i < a.length; i++) {
            a[i] = sc.nextInt();
        }
        System.out.println("原数组为:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]);
        }
        System.out.println();
    }
    //修改数组
    public static void ChangeArr(int[] a){
        int[] b = new int[a.length];
        for (int i = 0; i < a.length; i++) {
            b[i] = a[i] + 5;
            b[i] = b[i] % 10;
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = b[a.length -1 - i];
        }
        System.out.println("加密数组:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i]);
        }
    }
//    原数组为:
//            8725
//    加密数组:
//            0723

9.7 双色球系统开发

  1. 需求
    随机生成一组中奖号码;中奖号码有6个红球(1~33,且不相同)和1个蓝球(1~16)组成。
    在这里插入图片描述

用户输入一组双色球号码;
判断中奖情况
2. 分析

    public static void main(String[] args) {
        // 初始化中奖号码和猜测号码
        int[] trueArr = new int[7];
        int[] guessArr = new int[7];
        trueNum(trueArr);
        guessNum(guessArr);
        judge(trueArr, guessArr);
    }

    // 生成中奖号码
    public static void trueNum(int[] a){
        Random rd = new Random();
        System.out.print("生成中奖号码: ");
        for (int i = 0; i < a.length - 1; i++) {
            //方法1:
//            a[i] = rd.nextInt(33) + 1;
//            // 确保中奖号码的各位不相同
//            if (i > 0) {
//                for (int j = 0; j < i; j++){
//                    if(a[i] == a[j]){
//                        a[i] = rd.nextInt(33) + 1;
//                        j = -1;
//                    }
//                }
//            }
            //方法2:
            while(true){
                int temp = rd.nextInt(33)+ 1;
                boolean flag = true;//标志位:初始化新加入的号码与之前不相同
                // 确保中奖号码的各位不相同
                for (int j = 0; j < i; j++) {
                    if (a[j] == temp){
                        flag = false;
                        break;
                    }
                }
                //如果新加入的号码与之前不相同,则赋值给数组
                if (flag){
                    a[i] = temp;
                }
            }
        }
        a[a.length-1] = rd.nextInt(16) + 1;
        printArr(a);
    }

    // 输出数组
    public static void printArr(int[] a){
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    // 猜测中奖号码
    public static void guessNum(int[] a){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入猜测号码(前六位1~33,第七位1~16):");
        for (int i = 0; i < a.length; i++) {
            System.out.print("第" + (i+1) + "位:");
            a[i] = sc.nextInt();
        }
        System.out.println("猜测中奖号码:");
        printArr(a);
    }

    // 判断中奖情况
    public static void judge(int[] a, int[] b){
       // 红球蓝球命中数量
        int red = 0;
        int blue = 0;
        for (int i = 0; i < a.length-1; i++) {
            if (a[i] == b[i]){
                red++;
            }
        }
        if (a[a.length - 1] == b[a.length - 1]){
            blue++;
        }
        // string: + 做连接
        switch ("red + '+' + blue"){
            case "6+1":
                System.out.println("1等奖:1000万元");
                break;
            case "6+0":
                System.out.println("2等奖:500万元");
                break;
            case "5+1":
                System.out.println("3等奖:3000元");
                break;
            case "5+0":
            case"4+1":
                System.out.println("4等奖:200元");
                break;
            case"4+0":
            case"3+1":
            case"2+1":
                System.out.println("5等奖:10元");
                break;
            case"1+1":
            case"0+1":
                System.out.println("6等奖:5元");
                break;
            default:
                System.out.println("未中奖!");
                break;
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值