JAVA——方法

public static 返回值类型 方法名(参数){
        //方法体
        return 数据;
}

一、定义与调用

public class demo9_12 {
    public static void main(String[] args) {
        // 调用
        myName();
    }
    //定义
    public static void myName(){
        System.out.println("Hello World");
    }
}

运行

 

二、含参数方法 

return返回值

public class demo9_12 {
    public static void main(String[] args) {
        //调用
        getMax();
        getMax2(100,200);
        getMax3(100,200,300);
        getMax4(100,200); 
    }

    public static void getMax() {
        int a = 100;
        int b = 200;
        int max = a > b ? a : b;
        System.out.println("最大值是:" + max);
    }


    //含参数方法
    public static void getMax2(int num1, int num2) {
        int max = num1 > num2 ? num1 : num2;
        System.out.println("最大的是:"+max);
    }

    //可变参数
    public static void getMax3(int... num) {

    }

    //return,返回值,结束,void换成对应类型
    public static int getMax4(int num1, int num2) {
        int max = num1 > num2 ? num1 : num2;
        System.out.println("最大的是:"+max);
        return max;
    }

}

三、练习

检测是否为整数

public class demo9_12 {
    public static void main(String[] args) {
        boolean result = isEvenNumber(200);
        if (result) {
            System.out.println("是偶数");
        }else{
            System.out.println("不是偶数");
        }
    }

//    public static boolean isEvenNumber(int num) {
//        if (num % 2 == 0) {
//            return true;
//        } else {
//            return false;
//        }
//    }

//    public static boolean isEvenNumber(int num) {
//        if (num % 2 == 0) {
//            return true;
//        }
//        return false;
//    }

//    public static boolean isEvenNumber(int num) {
//        return num % 2 == 0 ? true : false;
//    }

    public static boolean isEvenNumber(int num) {
        return num % 2 == 0;
    }
}

检测一个三位数是否为水仙花数

import java.util.Scanner;

public class demo9_12_2 {
    public static void main(String[] args) {
        System.out.println("请输入三位数:");
        Scanner sc = new Scanner(System.in);
        boolean result = isNarcissisticNumber(sc.nextInt());
        System.out.println(result?"是水仙花数":"不是水仙花数");
    }

    public static boolean isNarcissisticNumber(int num) {
        if (num < 100||num >999) {
            return false;
        }
        int one = (int) Math.pow(num % 10, 3);
        int ten = (int) Math.pow(num / 10 % 10, 3);
        int hundred = (int) Math.pow(num / 100 % 10, 3);
        return (one + ten + hundred == num);
    }
}

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值