1. package com.itheima.demo;
    2. public class Test1 {
    3. public static void main(String[] args) {
    4. // 需求:使用方法计算1 - n的和并返回
    5. System.out.println(sum(5));
    6. }
    7. public static int sum(int n){
    8. // 用循环的方式计算 int sum 这个容器变量要定义在方法里面
    9. int sum = 0; // 定义一个变量名用于装遍历的变量,sum名字一样不会冲突,一个是变量名,一个是方法名
    10. for (int i = 1; i <= n; i++) {
    11. sum += i;
    12. }
    13. return sum;
    14. }
    15. }
    1. package com.itheima.demo;
    2. public class Test2 {
    3. public static void main(String[] args) {
    4. // 需求:判断一个整数是奇数还是偶数 并进行结果的输出 使用方法完成
    5. check(10);
    6. }
    7. public static void check(int n){ // 这里可以定义一个void类型的数据,不需要返回值,直接输出
    8. if (n % 2 == 0){
    9. // 一般看到方法中有sout语句,方法返回值类型都为void
    10. System.out.println(n + "是偶数");
    11. }else {
    12. System.out.println(n + "是奇数");
    13. }
    14. }
    15. }
    1. package com.itheima.demo;
    2. public class Test3 {
    3. public static void main(String[] args) {
    4. // 需求:使用方法,支持找出任意整型数组的最大值返回
    5. int[] ages = {18,20,30,32,23}; // 先写一个数组,然后赋值到方法中,因为方法是接收数组类型的数据
    6. int max = getArrayMaxData(ages); // 不同方法里面的变量,可以取一样的名字
    7. System.out.println("该数组最大值为:" + max);
    8. }
    9. public static int getArrayMaxData(int[] arr){ // 返回值类型为int因为返回最大值,形参是int[]数组类型
    10. // 找出数组的最大值返回
    11. // 先定义一个比较值,一般取第一个元素
    12. int max = arr[0];
    13. for (int i = 0; i < arr.length; i++) {
    14. if (arr[i] > max){
    15. max = arr[i];
    16. }
    17. }
    18. return max;
    19. }
    20. }