面向对象构造方法(无参无返回值和有参有返回值)

1:写一个牌的类,类中有属性:花色、值。
    2:有一个展示此牌信息的方法show(输出格式:如'梅花5')
    3:在main方法内,创建一张牌,将此牌的花色设为“梅花”,值设为5。
    4:最后显示此牌的信息

无参无返回值

public class brand {
    String flowercolor ;
    int zhi ;
    public void show(){
        System.out.println(flowercolor + zhi);
    }

    public static void main(String[] args) {
        brand b = new brand();
        b.zhi = 5 ;
        b.flowercolor = "梅花";
        b.show();
    }
}

 1:写一个计算器的类,属性:n1,n2
    类中有2个方法:
       (一) 输出两数之和                            【无参有返回】
     (二)计算返回平均分。                   【无参有返回】


public class JS {
    int n1 ;
    int n2 ;
    public int he(){
        return n1 + n2 ;
    }
    public int avg(){
        return (n1 + n2)/2;
    }

    public static void main(String[] args) {
        JS js = new JS();
        js.n1 = 10 ;
        js.n2 = 30 ;
        int he = js.he();
        int avg = js.avg();
        System.out.println("和为: "+he);
        System.out.println("平均分为: "+avg);
    }
}

 有参有返回值

 1、传入一个整数,返回是否为偶数(返回值类型为boolean)


public class Demo1 {
    public boolean show(int num){//返回值为boolean
        boolean flag = false ;
        if (num%2==0){
            return true ;
        }
        return flag ;
    }

    public static void main(String[] args) {
        Demo1 demo1 = new Demo1();
        boolean flag1 = demo1.show(10);//num= 10 ;
        if (flag1){
            System.out.println("偶数");
        }else {
            System.out.println("奇数");
        }
    }
}

2、传入一个整数数组,返回数组中的最大值


public class Demo2 {
    public int shu(int[] num){
        int max = num[0];//假设第一个值最大
        for (int i = 0; i < num.length; i++) {
            if (num[i]>max){//通过比较得出最大值
                max = num[i];
            }
        }
        return  max ;
    }
    public static void main(String[] args) {
        Demo2 demo2 = new Demo2();
          int[] n = {1,2,3,4,5,6};//对应的下标为0,1,2,3,4,5
         int jg = demo2.shu(n);//取出变量里面的值
        System.out.println("最大值为: "+jg);

    }
}

3、传入二个整数,返回最大值


public class Demo3 {
    public int shu(int n1 ,int n2){
        int max = 0 ;
        if (n1>n2){
            max = n1 ;
        }else {
            max = n2 ;
        }
        return max ;
    }

    public static void main(String[] args) {
        Demo3 demo3 = new Demo3();
        int jg = demo3.shu(10,20);
        System.out.println("二个数比较后的最大值为: " +jg);
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值