JAVA小白 编程练习500题 超详细!!!带答案!!!持续更新中~_java练习-程序员宅基地

技术标签: java  拓展补充  编程  基础  练习题  笔试  

JAVA小白编程题练习

可能有很多刚入门的小白不知道自己如何能快速提升编程技巧与熟练度
其实大佬进阶之路只有一个~ 那就是疯狂码代码!!!实践出真知!!!
所以为了大家能够想练习的时候有素材,泡泡给大家整理了一些练习题
由于平时比较忙,所以我在不定时努力更新中,欢迎监督~
500是立的Flag啊哈哈哈哈,我们共同努力吧,本帖已满,以下为第二个练习帖的链接:

练习帖2 点我点我

希望能给大家带来帮助~

文章目录

练习题:通过代码编写,输出一句话:“我要开始学习JAVA了,今天又是知识量满满的一天~”

package cn.cxy.exec;

public class TestPrint {
    
    public static void main(String[] args) {
    
        System.out.println("我要开始学习JAVA了,今天又是知识量满满的一天~");
    }
}

练习题:打印个人信息案例,将一个人的一些个人信息打印输出

package cn.cxy.exec;

public class TestPrint2 {
    
    public static void main(String[] args) {
    
        System.out.println("海绵宝宝");//字符串类型,我是海绵宝宝
        System.out.println(3);//整数类型,今年3岁了
        System.out.println("海底");//字符串类型,我的家在海底
        System.out.println(true);//布尔类型,吃饭了吗?吃啦,吃的蟹黄堡
        System.out.println(10.99);//浮点类型,今天还收到了10.99的红包
    }
}

练习题:拼接打印:输出:XXX:这是我学习JAVA的第X年,我的期望薪资是XXX

package cn.cxy.exec;

public class TestPrint3 {
    
    public static void main(String[] args) {
    
        //1.定义变量保存姓名
        String name = "派大星";
        //2.定义变量保存年份
        int year = 1;
        //3.定义变量保存期望薪资
        double salary = 10000.0;
        //4.拼接打印目标结果
        System.out.println(name+":这是我学习JAVA的第"+year+"年,我的期望薪资是"+salary);
    }
}

练习题:定义两个整数,计算这两个整数加减乘除运算的结果,并把结果打印到控制台

package cn.cxy.exec;

public class TestPrint4 {
    
    public static void main(String[] args) {
    
        //1.定义变量保存要计算的第一个数
        int number1 = 1;
        //2.定义变量保存要计算的第二个数
        int number2 = 2;
        //3.打印输出这两个数计算的结果
        System.out.println(number1+number2);
    }
}

练习题:预测身高案例:

其实我们可以通过父母的身高大致推断出子女的身高,假定父母与子女的身高遗传关系如下:
​ 儿子身高(厘米)=(父亲身高+母亲身高) ×1.08÷2
​ 女儿身高(厘米)=(父亲身高×0.923+母亲身高) ÷2
那已知:现有父亲身高175CM,母亲身高160CM。
请将预测的子女身高打印输出

package cn.cxy.exec;

public class TestPrint5 {
    
    public static void main(String[] args) {
    
        //1.定义变量保存父亲的身高
        double fatherHeight = 175;
        //2.定义变量保存母亲的身高
        double motherHeight = 160;
        //3.计算儿子身高
        double sonHeight = (fatherHeight + motherHeight) * 1.08 / 2;
        //4.计算女儿身高
        double daughterHeight = (fatherHeight * 0.923 + motherHeight) / 2;
        //5.打印输出最终计算的结果
        System.out.println("儿子预计身高" + sonHeight + "厘米");
        System.out.println("女儿预计身高" + daughterHeight + "厘米");
    }
}

练习题:逻辑判断

已知小红同学有25元,她攒了几天钱之后发现自己的现在的钱比原来的2倍还多出10块。而小蓝同学有30元,他攒了几天钱之后发现自己的钱正好是原来的2倍。于是小胖说:小红和小蓝现在的钱一样多,请问,他说的对吗?

package cn.cxy.exec;

public class TestPrint4 {
    
    public static void main(String[] args) {
    
        //1.定义变量保存小红原来的钱数
        int red = 25;
        //2.定义变量保存小蓝原来的钱数
        int blue = 30;
        //3.求小红同学现在的钱数
        red = red * 2 + 10;
        //4.求小蓝同学现在的钱数
        blue *= 2; //这是一种简写形式,等同于blue = blue *2;
        //5.判断并输出两个人的钱是否相等
        System.out.println(red == blue);
    }
}

练习题:最优选择

某小伙想定一份外卖,商家的优惠方式如下:鱼香肉丝单点24元,油炸花生米单点8元,米饭单点3元。订单满30元8折优惠。鱼香肉丝优惠价16元,但是优惠价和折扣不能同时使用。那么这个小伙要点这三样东西,最少要花多少钱?

public class Demo3 {
    
    public static void main(String[] args) {
    
        //1.求不使用优惠时的总价
        double money1 = 24 + 8 + 3;
        //2.判断折后总价
        money1 = (money1 <= 30 ? money1 : money1 * 0.8);
        //3.求使用优惠时的总价
        double money2 = 16 + 8 + 3;
        //4.判断两种花费哪个更少
        double money = money1 < money2 ? money1 : money2;
        //5.打印最终花费
        System.out.println(money);
    }
}

练习题: 接收用户输入的3个整数,并将它们的最大值作为结果输出

package cn.cxy.exec;

import java.util.Scanner;

public class GetMaxNumber {
    
    public static void main(String[] args) {
    
        //1.提示并接收用户输入的三个整数,并交由变量a b c来保存
        System.out.println("请输入第一个整数:");
        int a = new Scanner(System.in).nextInt();
        System.out.println("请输入第二个整数:");
        int b = new Scanner(System.in).nextInt();
        System.out.println("请输入第三个整数:");
        int c = new Scanner(System.in).nextInt();

        //2.对接收到的三个值进行比较
        /**三元运算符 1 ? 2 : 3
         * 如果1号位置的表达式结果为true,结果就取2号位置的值,反之,就取3号位置的值*/
        //2.1定义变量max来保存a和b中的最大值
        int max = a>b ? a : b;
        //2.2比较max与c谁最大,并将最大值交由max来保存
        max = max>c ? max : c;
        /**解决方案二:*/
        //int max = a>b?(a>c?a:c):(b>c?b:c);
        //3.输出结果
        System.out.println("三个数的最大值是:"+max);
    }
}

练习题:接收用户输入的数据,判断是奇数还是偶数

package cn.cxy.exec;

import java.util.Scanner;
public class TestNum {
    
	public static void main(String[] args) {
    
		//1.提示并接收用户输入的数据
		System.out.println("请输入您要判断的数据");
		int input = new Scanner(System.in).nextInt();
		//2.判断用户输入的数据
		if(input % 2 == 0) {
    
			System.out.println(input+"是偶数");
		}else {
    
			System.out.println(input+"是奇数");
		}
	}
}

练习题:输入数字1~7,输出对应星期几

package cn.cxy.exec;

import java.util.Scanner;

public class TestDay {
    
	public static void main(String[] args) {
    
		//1.提示并接收用户输入的数据
		System.out.println("请输入数据:");
		int input = new Scanner(System.in).nextInt();
		//2.判断用户输入的数据
		if(input == 1) {
    
			System.out.println("星期一");
		}else if(input == 2){
    
			System.out.println("星期二");
		}else if(input == 3){
    
			System.out.println("星期三");
		}else if(input == 4){
    
			System.out.println("星期四");
		}else if(input == 5){
    
			System.out.println("星期五");
		}else if(input == 6){
    
			System.out.println("星期六");
		}else if(input == 7){
    
			System.out.println("星期日");
		}
	}
}

练习题: BMI 指数测试 BMI = 体重 (kg) / 身高² (m)

接收用户输入的身高和体重,将判断结果输出
过轻:低于18.5
正常:18.5 ~ 22.9
偏胖:23 ~ 24.9
肥胖:25 ~ 29.9
重度肥胖:高于30
极度肥胖:高于40

package cn.cxy.exec;

import java.util.Scanner;

public class TestBMI {
    
    public static void main(String[] args) {
    
        //1.提示并接收用户输入的身高与体重信息
        System.out.print("请输入您的身高(单位为m):");
        double height = new Scanner(System.in).nextDouble();
        System.out.print("请输入您的体重(单位为kg):");
        double weight = new Scanner(System.in).nextDouble();

        //2.调用getBMI()方法,根据身高和体重信息,输出结果
        getBMI(height, weight);
    }

    public static void getBMI(double h, double w) {
    
        //求出BMI指数
        double bmi = w / (h * h);
        //定义一个变量r来保存最终结果
        String r = "";

        //根据 bmi 指数范围,来给r重新赋值
        if (bmi < 18.5) {
    
            r = "过轻";
        } else if (bmi <= 22.9) {
    
            r = "正常";
        } else if (bmi <= 24.9) {
    
            r = "偏胖";
        } else if (bmi <= 29.9) {
    
            r = "肥胖";
        } else if (bmi <= 40) {
    
            r = "重度肥胖";
        } else {
    
            r = "极度肥胖";
        }
        //打印最终结果
        System.out.println("您的BMI指数:" + bmi);

        System.out.println("您的体重属于:" + r);
    }
}

练习题:最优选择2

小蓝同学想买一个价值8888元的新手机,她的旧手机在二手市场能卖1880元,而手机专卖店推出以旧换新的优惠,把她的旧手机交给店家,新手机就能够打7.5折优惠。为了更省钱,小蓝要不要以旧换新?

public class TestChoice {
    
    public static void main(String[] args) {
    
        //1.计算不使用以旧换新的花费
        int plan1 = 8888 - 1880;
        //2.计算以旧换新的花费
        double plan2 = 8888 * 0.75;
        //3.判断两种方式
        if(plan1 > plan2){
    
            System.out.println("使用以旧换新更省钱");
        }else{
    
            System.out.println("不使用以旧换新更省钱");
        }
    }
}

练习题:求数字的绝对值

绝对值是指一个数在数轴上所对应点到原点的距离,用“| |”来表示。负数的绝对值是他去掉负号以后的值,而非负数(0和正数)的绝对值是他本身。请定义一个方法,接收用户输入的数字,输出绝对值结果。

package cn.cxy.exec;

import java.util.Scanner;

public class TestNum {
    
    public static void main(String[] args) {
    
        //1.接收用户输入的要测试的数字
        System.out.println("请输入你要判断的数字:");
        double input = new Scanner(System.in).nextDouble();
        //2.调用求绝对值的方法并拿到方法执行后的结果(返回值)
        double result = getAbsNum(input);
        //3.打印求出的结果
        System.out.println(input+"的绝对值是:"+result);
    }

    private static double getAbsNum(double input) {
    
        if(input >=0){
    //如果是非负数
            return input;//返回本身的值
        }else{
    //如果是负数
            return -input;//则值取反
        }
    }

}

练习题:求指定两个数的最大公约数和最小公倍数

package cn.cxy.exec;

import java.util.Scanner;

public class NumTest {
    
   public static void main(String[] args) {
    
      System.out.println("输入两个整数:");
      int a = new Scanner(System.in).nextInt();
      int b = new Scanner(System.in).nextInt();

      int d = zdgys(a,b);//调用求最大公约数的方法
      long x = zxgbs(a,b);//调用求最小公倍数的方法
      System.out.println("最大公约数:"+d);
      System.out.println("最小公倍数:"+x);
   }

   private static int zdgys(int a, int b) {
    
      int min = a<b ? a : b;
      for(int i=min; i>=1; i--) {
    
         //i能把a和b同时整除
         if(a%i==0 && b%i==0) {
    
            return i;
         }
      }
      //这句代码根本不会执行,
      //让编译可以通过
      return 0;
   }

   private static long zxgbs(int a, int b) {
    
      int max = a>b? a : b;
      for(long i=max; ;i+=max) {
    
         //i能同时被a和b整除
         if(i%a==0 && i%b==0) {
    
            return i;
         }
      }
   }

}

练习题:银行收入计算

某银行推出了整存整取定期储蓄业务,其存期分为一年、两年、三年、五年,到期凭存单支取本息。存款年利率表如下:
​ 存期 年利率(%)
​ 一年 2.25
​ 两年 2.7
​ 三年 3.25
​ 五年 3.6
请存入一定金额(1000起存),存一定年限(四选一),计算到期后得到的本息总额。
提示:
​ 存入金额和存入年限均由键盘录入
​ 本息计算方式:本金+本金×年利率×年限

import java.util.Scanner;
public class BankDemo {
    
    public static void main(String[] args) {
    
        //1.提示并接收用户输入的存款金额
        System.out.println("请输入存款金额:");
        int money = new Scanner(System.in).nextInt();
        //2.提示并接收用户输入的存款年限
        System.out.println("请输入存款年限:");
        int year = new Scanner(System.in).nextInt();
        //3.定义变量用来保存本金和利息之和
        double outMoney = 0;
        //4.根据利率和年限计算本息和
        if (year == 1) {
    
            outMoney = money + money * 2.25 / 100 * 1;
        } else if (year == 2) {
    
            outMoney = money + money * 2.7 / 100 * 2;
        } else if (year == 3) {
    
            outMoney = money + money * 3.25 / 100 * 3;
        } else if (year == 5) {
    
            outMoney = money + money * 3.6 / 100 * 5;
        } else {
    
            System.out.println("输入的年限有误");
        }
        //5.打印输出
        System.out.println("存款" + year + "年后的本息是:" + outMoney);
    }
}

练习题:求税后工资问题

2019年1月1日起,国家推出新的个人所得税政策,起征点上调值5000元。也就是说税前工资扣除三险一金(三险一金数额假设是税前工资的10%)后如果不足5000元,则不交税。如果大于5000元,那么大于5000元的部分按梯度交税,具体梯度比例如下:
​ 0 ~ 3000元的部分,交税3%
​ 3000 ~ 12000元的部分,交税10%
​ 12000 ~ 25000的部分 , 交税20%
​ 25000 ~ 35000的部分,交税25%
​ 35000 ~ 55000的部分,交税30%
​ 55000 ~ 80000的部分,交税35%
​ 超过80000的部分,交税45%
比如:小蓝入职一家企业后,税前工资是18000,则他每月该交个税的部分是18000-1800-5000=11200元,个税缴纳数额是3000×3%+8200×10%=910元。税后工资15290元。
请完成一个个税计算程序,在用户输入税前工资后,计算出他对应的纳税数额,以及税后工资为多少?

import java.util.Scanner;
public class Demo5 {
    
    public static void main(String[] args) {
    
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入您的税前工资:");
        //2.键盘录入税前工资
        int money = sc.nextInt();
        //3.计算应纳税部分的工资
        double before = money - (money*0.1) - 5000;
        //4.定义个税变量
        double shui = 0;
        //5.按照梯度范围计算个税数值
        if(before > 0 && before <=3000){
    
            shui = before * 0.03;
        }else if(before > 3000 && before <=12000){
    
            shui = 3000*0.03 + (before-3000) * 0.1;
        }else if(before > 12000 && before <=25000){
    
            shui = 3000*0.03 + 9000*0.1 +  (before-12000)*0.2;
        }else if(before > 25000 && before <=35000){
    
            shui = 3000*0.03 + 9000*0.1 + 13000*0.2 + (before-25000)*0.25;
        }else if(before > 35000 && before <=55000){
    
            shui = 3000*0.03 + 9000*0.1 + 13000*0.2 + 10000*0.25 + (before-35000)*0.3;
        }else if(before > 55000 && before <=80000){
    
            shui = 3000*0.03 + 9000*0.1 + 13000*0.2 + 10000*0.25 + 20000*0.3 + (before-55000)*0.35;
        }else if(before > 80000){
    
            shui = 3000*0.03 + 9000*0.1 + 13000*0.2 + 10000*0.25 + 20000*0.3 + 25000*0.35 + (before-80000)*0.45;
        }
        //6.计算税后工资
        double after = money - (money*0.1) - shui;
        //7.打印个税和税后工资
        System.out.println("个人所得税" + shui + "元");
        System.out.println("税后工资" + after + "元");
    }
}

练习题: 手机选号:根据用户输入的手机号来确认用户实际支付的价格

如果尾数为8,需支付办卡费50元
如果尾数为4,需支付办卡费用0元
如果是其他尾号,需支付办卡费用20元

package cn.cxy.exec;

import java.util.Scanner;

public class PayCard {
    
    public static void main(String[] args) {
    
        //1.提示并接收用户输入的手机号
        System.out.println("请输入您预选的手机号:");
        String tel = new Scanner(System.in).nextLine();//注意String类型数据一般用nextLine()

        //2.调用getPrice()方法,来计算价格,注意需要把手机号tel作为参数传入方法中
        getPrice(tel);
    }

    //3.创建getPrice()
    public static void getPrice(String tel) {
    
        //3.1 手机号tel的长度,必须是11位的正确手机号--提前校验,提高程序健壮性
        if(tel.length() != 11) {
    
            System.out.println("号码格式错误");
            return;//结束方法,返回到调用位置再继续执行
        }

        /*比如我们拿到的手机号是tel="2313123123",想要拿到尾数,也就是最后一个字符
         * 需要用到 char c = tel.charAt(10)
         * 注意:由于下标也是从0开始,所以取第11个字符,它的下标位置是10
         */
        //3.2获取手机号的尾数
        char c = tel.charAt(10);

        //3.2定义用来保存最终结果的变量price,初始值为0
        int price = 0;

        //3.3根据c字符的值,来为price重新赋值
        switch(c) {
    
            case '8': price=50; break;//尾数为8支付50
            case '4': price=0; break;//尾数为4免费
            default: price=20;//其他情况需支付20
        }
        //3.4显示结果
        System.out.println("您实际应支付的价格为:"+price);
    }
}

练习题: 获取邮箱名字

接收用户输入的邮箱名,获取邮箱的名字
比如:[email protected],输出cxy

package cn.cxy.exec;

import java.util.Scanner;

public class GetEmailName {
    
	public static void main(String[] args) {
    
		System.out.println("输入email:");
		String e = new Scanner(System.in).nextLine();
		//email地址e,传递到该方法,
		//并得到方法返回的名字,保存到变量n
		String n = getName(e);
		System.out.println(n);
	}

	static String getName(String email) {
    
		/*
		 * "[email protected]"
		 *         |
		 *         index
		 *
		 * 1. 定位 "@" 的下标位置 index
		 * 2. 截取 [0, index),直接返回
		 * email.indexOf("@")
		 *        查找指定子串的位置
		 *        找不到,得到特殊值 -1
		 * email.substring(0, index)
		 *        截取 [0, index)
		 */
		//找@的位置
		int index = email.indexOf("@");
		if(index == -1) {
    //找不到
			return "邮箱格式错误";
		}
		//截取,直接返回截取的结果
		return email.substring(0, index);
	}
}

练习题 : 分别通过for循环/While循环/do-While循环写一个死循环

package cn.cxy.exec;

public class DeadCycle {
    
    public static void main(String[] args) {
    
        //for循环的死循环
//        for (int i = 1; ; i++){
    
//            System.out.println("欢迎学习泡泡的分享,继续加油哦~");
//        }
        //while循环的死循环
//        while(true){
    
//            System.out.println("都到这里啦?奥利给~");
//        }
        //do-while循环的死循环
        do{
    
            System.out.println("相信我们可以的~");
        }while(true);
    }
}

练习题: 鸡兔同笼问题(穷举法)

已知:鸡兔共35,94只脚,那么鸡和兔各几只?
package cn.cxy.exec;
//穷举法
//鸡    兔
//0     35
//1     34
//2     33
//3     32
//...
//23    12
//...
//35    0
public class SameCage {
    
    public static void main(String[] args) {
    
        //循环变量j,控制小鸡的个数: 0到35递增
        //循环变量t,控制兔子的个数: 35到0递减
        for(int j=0,t=35; j<=35; j++,t--) {
    //如果有多个小条件,用逗号隔开
            //保证脚的数量是94
            if(j*2 + t*4 == 94) {
    
                System.out.println("鸡:"+j+", 兔:"+t);
            }
        }
    }
}

练习题:商品录入系统

通过java基础的相关知识,设计并完成一个简单的商品录入系统,可以实现:菜单显示、商品信息展示、商品信息录入、商品信息查询、退出的功能

package cn.cxy.exec;

import java.util.Scanner;

public class Product {
    
   //成员变量
   static String[] names = {
    "iPhoneXS","华为 Mate 20 pro","小米X","vivo NEX","oppo Find"};
   static double[] price = {
    8999,5399,2399,4399,3999};
   static int[] numbers =  {
    50,20,80,120,90};

   public static void main(String[] args) {
    
      /*
       * ----------------------
       * 1. 商品列表
       * 2. 商品录入
       * 3. 商品查询
       * 4. 统计信息
       * 5. 退出
       * ----------------------
       * 选择:> 1
       * ....
       */

      //死循环显示菜单
      outer:
      while(true) {
    
         //显示菜单,并获得选择的值
         int c = menu();
         //判断c的值
         switch(c) {
    
         case 1: f1(); break;
         case 2: f2(); break;
         case 3: f3(); break;
         case 4: f4(); break;
         case 5: break outer;
         }
      }
   }

   private static int menu() {
    
      System.out.println("----------------------");
      System.out.println("1. 商品列表");
      System.out.println("2. 商品录入");
      System.out.println("3. 商品查询");
      System.out.println("4. 统计信息");
      System.out.println("5. 退出");
      System.out.println("----------------------");
      System.out.print("选择:> ");
      return new Scanner(System.in).nextInt();
   }

   private static void f1() {
    
      /*
         names
         ["A", "B", "C"]
         price
         [2,    8,    3]
         numbers
         [200,  300,  180]
           0     1    2
         1. 名称:xx,价格:xx,数量:xx
       */
      for(int i=0;i<names.length;i++) {
    
         String n = names[i];
         double p = price[i];
         int b = numbers[i];
         System.out.println(
          (i+1)+". 名称:"+n+",价格:"+p+",数量:"+b);
      }
   }

   private static void f2() {
    
      /*
         names
         ["A", "B", "C"]
         price
         [2,    8,    3]
         numbers
         [200,  300,  180]
          0     1    2
      */
      //遍历数组
      for (int i = 0; i < names.length; i++) {
    
         System.out.println("录入第"+(i+1)+"件商品:");
         System.out.print("名称:");
         String n = new Scanner(System.in).nextLine();
         System.out.print("价格:");
         double p = new Scanner(System.in).nextDouble();
         System.out.print("数量:");
         int b = new Scanner(System.in).nextInt();
         names[i] = n;
         price[i] = p;
         numbers[i] = b;
      }
      //重新显示商品列表
      f1();
   }

   private static void f3() {
    
      /*
         names
         ["A", "B", "C"]
         price
         [2,    8,    3]
         numbers
         [200,  300,  180]
          0     1    2
        字符串,比价是否相等,要用equals()方法
        a = "aaa"
        b = "aaa"
        a.equals(b)
       */
      System.out.print("输入查询的商品名:");
      String n = new Scanner(System.in).nextLine();
      //遍历数组
      for (int i = 0; i < names.length; i++) {
    
         // n 和 names[i] 相等
         if(n.equals(names[i])) {
    
            String name = names[i];
            double p = price[i];
            int b = numbers[i];
            System.out.println(
             (i+1)+". 名称:"+name+",价格:"+p+",数量:"+b);
            return;
         }
      }
      //循环结束,所有商品都比较完,没有找到
      System.out.println("找不到商品");
   }

   private static void f4() {
    
      /*
         names
         ["A", "B", "C"]
         price
         [2,    8,    3]
         numbers
         [200,  300,  180]
              0     1     2
       */
      //商品总价,单价均价,最高单价,最高总价
      double spzj = 0;//商品总价
      double djzj = 0;//单价总价
      double zgdj = 0;//最高单价
      double zgzj = 0;//最高总价
      //遍历数组
      for (int i = 0; i < names.length; i++) {
    
         spzj += price[i] * numbers[i];
         djzj += price[i];
         //数组中,找到更大的值
         if(price[i] > zgdj) {
    
            zgdj = price[i];//更大值存到这个变量
         }
         if(price[i]*numbers[i] > zgzj) {
    
            zgzj = price[i]*numbers[i];
         }
      }
      System.out.println("商品总价:"+spzj);
      System.out.println("单价均价:"+(djzj/names.length));
      System.out.println("最高单价:"+zgdj);
      System.out.println("最高总价:"+zgzj);
   }
}

练习题:求数字阶乘(for循环版)

需求:接收用户输入的数字,计算该数字的阶乘结果
已知:负数不可以有阶乘,0的阶乘结果是1,
5 ! = 5 x 4 x 3 x 2 x 1

package cn.cxy.exec;

import java.util.Scanner;

public class Factorial {
    
    public static void main(String[] args) {
    
        System.out.print("输入整数,求阶乘:");
        int n = new Scanner(System.in).nextInt();
        //调用f()方法,把n的值传递到f()方法,求阶乘
        f(n);
    }

    public static void f(int n) {
    
        if(n<0) {
    
            System.out.println("负数不可以求阶乘");
            return;//方法结束,返回到调用位置继续执行
        }
        if(n == 0) {
    
            System.out.println("0的阶乘是1");
            return;
        }
        /*
         * r = 5
         * i
         * 4, r=r*i
         * 3, r=r*i
         * 2, r=r*i
         * 1, r=r*i
         */
        long r = n;
        for(int i=n-1; i>=1; i--) {
    
            r *= i;
        }
        System.out.println(n+"的阶乘:"+r);
    }
}
/**其实我们还可以通过递归思想解决这个问题,感兴趣的可以研究一下~*/

练习题:多次生成随机数,并打印第一次出现大于0.999 时的次数与生成的随机数

package cn.cxy.exec;

public class ForBreak {
    
    public static void main(String[] args) {
    
        // Math.random()可以产生[0,1)的随机浮点数
        // >0.999
        //写一个死循环, i变量用来计次
        for(int i=1; ;i++) {
    
            double d = Math.random();
            if(d>0.999) {
    
                System.out.println("第"+i+"次产生了目标值,值为:"+d);
                break;
            }
        }
    }
}

练习题:打印100以内除了尾数为3,5,7的所有数

package cn.cxy.exec;

public class ForContinue {
    
    public static void main(String[] args) {
    
        for(int i=1;i<=100;i++) {
    
            int y = i%10;//100以内的数,通过取余求出尾数
            if(y==3 || y==5 || y==7) {
    
                continue;//如果尾数为3 5 7 ,则跳过后面的打印,进行下一轮循环
            }
            System.out.println(i);
        }
    }
}

练习题:求质数:接收用户输入的数字,判断是否为质数

质数的概念:一个大于1的自然数,除了1和它自身外,不能被其他自然数整除的数叫做质数,也称为素数
规定:1既不是质数,也不是合数

package cn.cxy.exec;

import java.util.Scanner;

public class PrimeNumber {
    
    public static void main(String[] args) {
    
        System.out.print("请输入要判断的自然数:");
        int n = new Scanner(System.in).nextInt();
        //调用getPrimeNumber()方法,判断n是否为质数
        getPrimeNumber(n);
    }
    public static void getPrimeNumber(int n) {
    
        if(n<2) {
    //此范围内的数均不为质数
            System.out.println(n+"不是质数");
            return;//结束程序
        }
        if(n == 2) {
    
            System.out.println("2是质数");
            return;
        }
        //在 2到 1+n开方范围(数学理论),找能把n整除的值(这个值也称作因子)
        //如果找到可以把n整除的第三个数,那n就不是质数,反之,n为质数
        double max = 1+ Math.sqrt(n);//max保存的是查找因子的范围

        //依次遍历范围内的所有数,验证是否存在n的因子
        for(int i=2; i<max; i++) {
    
            //判断n能不能被i整除,如果有,说明不是质数
            if(n%i == 0) {
    
                System.out.println(n+"不是质数");
                return;
            }
        }
        //如果判断了范围内的所有值,没有能整除的,则说明n是质数
        System.out.println(n+"是质数");
    }
}

练习题:接收用户输入的数字,判断在此范围内质数的个数

package cn.cxy.exec;

import java.util.Scanner;

public class CountPrimeNumber {
    
    public static void main(String[] args) {
    
        System.out.println("输入整数n,求n内质数的数量");
        int n = new Scanner(System.in).nextInt();

        count(n);
    }

    public static void count(int n) {
    
        if(n<2) {
    
            System.out.println("没有质数");
            return;
        }
        if(n==2) {
    
            System.out.println("有1个质数");
            return;
        }
        //定义计数变量
        int count = 1;//已知有一个质数
        outer:   //从3到n寻找质数
        for(int i=3; i<=n ;i++) {
    
            //判断i是否是质数
            double max = 1+ Math.sqrt(i);
            for(int j=2; j<max; j++) {
    //在2到<max,找能把i整除的数
                if(i%j == 0) {
    //i被j整除,i不是质数
                    //跳到i++,继续判断下一个i值
                    continue outer;//跳到外部outer的位置
                }
            }
            //内层j循环结束,i是质数
            count++;
        }
        System.out.println(n+"内质数的数量:"+count);
    }
}

练习题:生成一个顺序数组,将这个数组的元素打乱顺序后输出

package cn.cxy.exec;

import java.util.Arrays;
import java.util.Random;

public class ShuffleArray {
    
    public static void main(String[] args) {
    
        //调用f()方法,从方法获取一个int[]数组
        int[] a = f();
        //遍历打印数组数据
        for(int i=0; i<a.length; i++) {
    
            System.out.println(a[i]);
        }
        System.out.println("\n\n----------------");

        //把a数组,传递到 shuffle() 方法打乱顺序
        shuffle(a);
        //打印乱序后的数组
        System.out.println(Arrays.toString(a));
    }

    public static int[] f() {
    
        //新建int[]数组,长度5
        //再把它的内存地址存到变量 a
        int[] a = new int[5];
        //遍历访问5个位置,填入1,2,3,4,5
        for(int i=0; i<a.length; i++) {
    
            a[i] = i+1;
        }
        //返回数组,把数组返回到调用位置
        //本质是把数组地址返回去
        return a;
    }

    public static void shuffle(int[] a) {
    
        /*
         *        j
         * [4, 2, 3, 1, 5]
         *     i
         *
         * *) i循环遍历数组
         * *) 随机定位下标j与i交换
         */
        for (int i = 0; i < a.length; i++) {
    
            //随机下标j,范围:[0, a.length)
            int j = new Random().nextInt(a.length);
            int t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
    }
}

练习题:打印全三角形

需求:接收用户输入的行数,打印对应的全三角形,如图所示:
在这里插入图片描述
在这里插入图片描述

package cn.cxy.exec;

import java.util.Scanner;

public class PrintTraingle {
    
	public static void main(String[] args) {
    
		//1.提示并接收用户输入的行数:
		System.out.println("请输入您要打印星星的行数:");
		int n = new Scanner(System.in).nextInt();

		//2.开始打印图形
		//2.1外层循环控制打印的行数 i的取值范围:[1,n],一共n行
		for(int i=1;i<=n;i++){
    
			//2.2内层循环1
			//控制每行打印空格的个数 j的取值范围:[0,n-i),即1 2 3...
			for(int j=0;j<n-i;j++){
    
				System.out.print(" ");
			}
			//2.3内层循环2
			//控制每行打印星星的个数 k的取值范围:[1,2*i-1],即1 3 5 ...
			for(int k=1;k<=2*i-1;k++){
    
				System.out.print("*");
			}
			//2.4打印完本行所有内容后添加换行
			System.out.println();
		}
	}
}

练习题:模拟双色球生成案例

需求:体彩中有一项是双色球,要求在1-33号共33个红色球里选出6个,1-16号共16个蓝色球中选出一个作为中奖号码,请实现这个需求

package cn.cxy.exec;

import java.util.Arrays;
import java.util.Random;

public class ColorBall {
    
	public static void main(String[] args) {
    
		//准备两个号码数组
		int[] r = zbsz(33);//[1,2,3,4,5....33]
		int[] b = zbsz(16);//[1,2,3...16]
		System.out.println(Arrays.toString(r));
		System.out.println(Arrays.toString(b));
		//选择红球
		int[] red = selectRed(r);
		//选择蓝球
		int blue = selectBlue(b);
		System.out.println("红球:"+Arrays.toString(red));
		System.out.println("蓝球:"+blue);
	}
	private static int[] zbsz(int n) {
    //准备数组的方法
		//新建n个长度的int[]数组,存到a
		int[] a = new int[n];
		//遍历a数组,填入1到n
		for (int i = 0; i < a.length; i++) {
    
			a[i] = i+1;
		}
		//返回数组
		return a;
	}
	private static int[] selectRed(int[] r) {
    //选择红球
		/*
		 *                                           j
		 * r [10, 5, 1, 4, 2, 6, 7, 8, 9, 3, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
		 *                       i
		 *       
		 *         [i, r.length)
		 *      i+ [0, r.length-i)
		 */
		//i循环从0到<6
		for (int i = 0; i < 6; i++) {
    
			//j随机定位
			int j =
					i+ new Random().nextInt(r.length-i);
			int t = r[i];
			r[i] = r[j];
			r[j] = t;
		}
		//截取前6个位置,生成一个新数组返回
		return Arrays.copyOf(r, 6);
	}
	private static int selectBlue(int[] b) {
    //选择蓝球
		return b[new Random().nextInt(16)];
	}
}

练习题:求任意自然数各位数之和

接收用户输入的任意自然数,累计所有位数数字之和
需求:接收用户输入的行数,

package cn.cxy.exec;

import java.util.Scanner;

public class SumNum {
    
	public static void main(String[] args) {
    
		//1.提示并接收用户要计算的自然数:
		System.out.println("请输出您要求和的自然数:");
		int n = new Scanner(System.in).nextInt();
		//2.定义一个变量用来保存最终求和的结果
		int sum=0;
		//3.循环获取每一位上的数
		while(n!=0){
    
			//4.求当前的个位数,并将个位数累加
			sum = sum + (n%10);
			//5.去掉刚刚累加过的最后一位数,得到新的整数
			//比如刚刚的十位就变成了现在的个位
			n=n/10;
		}
		//6.打印最终的结果:
		System.out.println(sum);
	}

}

练习题:求任意数组中所有元素的最大值

package cn.cxy.exec;

public class GetArrayMaxNum {
    
		public static void main(String[] args) {
    
			//1.定义一个数组
			int[] arr={
    90,1562,43,2,44,8,6666};
			//2.选取数组中的第一个元素开始比较
			int max=arr[0];
			//3.依次遍历数组中的每个元素
			for(int i=1;i<arr.length;i++){
    //i指的是下标,我们通过下标来操作数组中的元素
				//4.判断当前元素与目前最大值的大小
				if(arr[i]>max){
    
					//5.如果当前数组元素大于max,就讲此元素的值赋值给max
					max=arr[i];
				}
			}
			//6.打印最终的结果
			System.out.println(max);
		}
	}

练习题:求1000以内的完数

完数:如果一个数等于其所有因子之和,我们就称这个数为"完数",比如6的因子为1,2,3 6 = 1 + 2 + 3,那么6就是一个完数

 package cn.cxy.exec;
/**获取1000以内的完数*/
public class GetNum {
    
	public static void main(String[] args) {
    
		//1.循环遍历1000以内的所有数
		for(int i=1;i<=1000;i++){
    
			//2.定义一个变量来保存求和的结果
			int sum = 0;
			//3.求i的因子
			for(int j=1;j<=i/2;j++){
    
				//4.判断是否能被整除
				if(i % j == 0){
    
					//5.如果能整除,就是因子,因子需要累加
					sum+=j;
				}
			}
			//6.如果因子累加之和为本轮判断的数,则当前数是完数,输出
			if(sum==i){
    
				System.out.println(i);

			}
		}
	}
}

练习题: 随机数组的归并问题

需求:生成两个任意的随机数组,并将这两个数组按照数字大小按顺序归并到一个新数组中

package cn.cxy.exec;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class  MergingArrays {
    
	   public static void main(String[] args) {
    
	      int[] a = suiJi();
	      int[] b = suiJi();
	      Arrays.sort(a);
	      Arrays.sort(b);
	      System.out.println(Arrays.toString(a));
	      System.out.println(Arrays.toString(b));
	      int[] c = heBing(a, b);
	      System.out.println(Arrays.toString(c));
	   }

	   private static int[] suiJi() {
    
	      int n = 5+ new Random().nextInt(6);
	      int[] a = new int[n];
	      for (int i = 0; i < a.length; i++) {
    
	         a[i] = new Random().nextInt(100);
	      }
	      return a;
	   }

	   private static int[] heBing(int[] a, int[] b) {
    
	      /*
	       * a[1,1,2,3,4]
	       *              j
	       * b[1,2,4,5,6,8,9]
	       *         k
	       *
	       * c[                     ]
	       *               i
	       */
	      //新建数组
	      int[] c = new int[a.length+b.length];
	      //对新数组遍历
	      for(int i=0,j=0,k=0;i<c.length;i++) {
    
	         if(j>=a.length) {
    //j越界,b数组数据一个一个放入新数组
	            //c[i] = b[k];
	            //k++;
	            //continue;
	            System.arraycopy(b,k,c,i,b.length-k);
	            break;
	         } else if(k>=b.length) {
    //k越界,a数组数据一个个放入新数组
	            //c[i] = a[j];
	            //j++;
	            //continue;
	            System.arraycopy(a,j,c,i,a.length-j);
	            break;
	         }
	         //j和k,较小值放入i位置,并递增
	         if(a[j]<=b[k]) {
    
	            c[i] = a[j];
	            j++;
	         } else {
    
	            c[i] = b[k];
	            k++;
	         }
	      }    
	      return c;
	   }
}

练习题:遍历二维数组打油诗

package cn.cxy.exec;

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class  TestArray {
    
	  public static void main(String[] args) {
    
	      char[][] a = {
    
	          //i
	         /*0*/{
    '道','路','千','万','条'},
	         /*1*/{
    '安','全','第','一','条'},
	         /*2*/{
    '行','车','不','规','范'},
	         /*3*/{
    '亲','人','两','行','泪'}
	             //0    1    2    3    4    j
	      };
	      /* j是外层循环,递增
	       *    i是内层循环,递减
	       * 亲行安道
	       * 人车全路
	       * 两不第千
	       */
	      for(int j=0;j<a[0].length;j++) {
    
	         for(int i=a.length-1; i>=0; i--) {
    
	            System.out.print(a[i][j]);
	         }
	         System.out.println();
	      }
	   }
}

练习题:求猴子大王

15个猴子围成一圈选大王,依次1-7循环报数,报到7的猴子被淘汰,直到最后一只猴子称为大王,问:哪只猴子会成为大王?

package cn.cxy.exec;
/**猴子选大王*/
public class MonkeyKing {
    
	public static void main(String[] args) {
    
		//1.定义长度为15的数组保存猴子,boolean类型是为了判断猴子是否存活
		boolean[] b=new boolean[15];

		//2.依次遍历每一只猴子
		//true---未淘汰  false---已淘汰
		for(int i=0;i<b.length;i++){
    
			b[i]=true;//先把所有猴子设置成存活
		}
		//3.定义变量保存猴子报的数
		int num=0;
		//4.定义变量保存剩余的猴子数
		int monkeyLeft=15;
		//5.定义数组下标
		int index=0;
		//6.循环,直到只剩最后一只猴子(猴子王)
		while(monkeyLeft>1){
    //判断条件
			//7.检测猴子是否已淘汰
			if(b[index]){
    
				//8.报数
				num++;
				//9.判断报数是否为7
				if(num==7){
    
					b[index]=false;//为7淘汰
					monkeyLeft--;//猴子数减一
					num=0;//报数归零
				}

			}

			//10.下标移动
			index++;
			//11.围成一圈---最后一个置为0
			if(index==15){
    
				index=0;
			}
		}

		//遍历数组,找到最后活着的那个猴子王
		for(int i=0;i<b.length;i++){
    
			if(b[i]){
    
				System.out.println(i+1);
			}
		}
	}
}

练习题:斐波那契问题

已知:斐波那契数列的前几个数分别为0,1,1,2,3,5…从第三项开始,每一项都等于前两项的和.请接收用户输入的整数n,求出此数列的前n项.

package cn.cxy.exec;

import java.util.Scanner;

/**斐波那契数列*/
public class Faibonacci {
    
	public static void main(String[] args) {
    
		System.out.println("请输入您要测试的数:");
		int n = new Scanner(System.in).nextInt();
		//判断n是否是不正常的范围
		if(n<1){
    
			System.out.println("输入数据有误!!!");
		}
		//n==1
		if(n==1){
    
			System.out.println(0);
		}
		//n==2
		if(n==2){
    
			System.out.println(0+"\t"+1);	
		}
		//n==3
		if(n==3){
    
			System.out.println(0+"\t"+1+"\t"+1);	
		}
		//拼接前n项
		if(n>3){
    
			System.out.print(0+"\t"+1+"\t"+1+"\t");	
		}
		//循环输出后面的数据
		int f1=1;
		int f2=1;
		int next=0;
		for(int i=4;i<=n;i++){
    
			next=f1+f2;
			f1=f2;
			f2=next;
			System.out.print(next+"\t");
		}
	}
}

练习题:古典问题:生兔兔问题

有一对兔子,从出生后第3个月起都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月兔子的对数为多少?
程序分析:前两个月兔子的对数为1
从第三个月开始,兔子的对数变成了 2 3 5 8 13 21 …

package cn.cxy.exec;

import java.util.Scanner;

public class GetRabbitNum {
    
	public static void main(String[] args) {
    
		System.out.println("请输入要判断的月数:");
		int month = new Scanner(System.in).nextInt();
		System.out.println("第"+month+"月兔子的对数为:"+getSum(month));
	}

	public static int getSum(int month) {
    
		//如果是前两个月,还是1对兔子
		if(month == 1 || month == 2) {
    
			return 1;
		}else {
    
			//从第三个开始,兔子按照2 3 5 8 13 21变化
			return getSum(month-1)+getSum(month-2);
		}
	}
}

练习题:打印水仙花数

水仙花数:是指一个三位数,其各位数字立方和等于该数字本身
例如:153就是一个水仙花数,因为153 = 1³ + 5³ + 3³

package cn.cxy.exec;

public class GetNum {
    
	public static void main(String[] args) {
    
		//1.遍历所有的三位数
		for (int i = 100; i < 1000; i++) {
    
			//2.调用自定义方法判断是不是水仙花数
			if(isAim(i)) {
    
				//3.如果是水仙花数,就打印
				System.out.println(i);
			}
		}
	}

	//4.自定义判断水仙花数的方法
	public static boolean isAim(int a) {
    
		int x = a/100;
		int y = a/10%10;
		int z = a%10;
		if(a == x*x*x+y*y*y+z*z*z) {
    
			return true;
		}
		return false;
	}
}

练习题:面向对象 封装百分制分数

需求:封装百分制分数,和它对应的五档分制分数

分数类:
package cn.cxy.exec;

public class Score {
    
	//成员变量
	int score;
	char level;
	//构造方法
	public Score(int score) {
    
		this.score = score;
		//计算五档分数,保存到成员变量level
		this.level = setLevel(score);
	}

	private char setLevel(int s) {
    
		char r = 0;
		switch(s/10) {
    
		case 10:case 9:
			r = 'A';break;
		case 8:case 7:
			r = 'B';break;
		case 6:
			r = 'C';break;
		case 5:case 4:case 3:case 2:
			r = 'D';break;
		case 1:case 0:
			r = 'E';break;
		}
		return r;

	}

	public String toString() {
    
		return score+", "+level;
	}
}
测试类:

package cn.cxy.exec;

public class TestScore {
public static void main(String[] args) {
/*
A [90,100]
B [70,90)
C [60,70)
D [20,60)
E [0,20)
*/
Score s = new Score(54);
System.out.println(s.toString());
}
}

练习题:面向对象 打印图形

需求:设计一个可以随机打印形状的代码

形状类【父类】:
package cn.cxy.exec;

public class Shape {
    
	public void draw() {
    
		//无意义代码
		//在子类中要重写draw()方法
		System.out.println("图形形状");
	}
	public void clear() {
    
		System.out.println("\n\n\n");
	}
}
圆形类【子类】:
package cn.cxy.exec;

public class Circle extends Shape {
    
	@Override
	public void draw() {
    
		System.out.println("打印一个圆形 O");
	}
}
方形类【子类】:
package cn.cxy.exec;

public class Square extends Shape {
    
	@Override
	public void draw() {
    
		System.out.println("打印一个方形 口");
	}
}
直线类【子类】:
package cn.cxy.exec;

public class Line extends Shape {
    
	@Override
	public void draw() {
    
		System.out.println("打印一条直线 ————");
	}

	public void length() {
    
		System.out.println("一米多。。。");
	}
}
测试类:随机生成图形
package cn.cxy.exec;

import java.util.Random;
import java.util.Scanner;

public class TestShape {
    
	public static void main(String[] args) {
    
		System.out.println("按回车继续");
		while(true) {
    
			int r = new Random().nextInt(4);
			switch(r) {
    
			case 0: f(new Shape()); break;
			case 1: f(new Line()); break;
			case 2: f(new Square()); break;
			case 3: f(new Circle()); break;
			}
		}
	}

	/*
	 * Shape
	 *   |- Line
	 *   |- Square
	 *   |- Circle
	 */
	static void f(Shape s) {
    
		System.out.println("----------------");
		new Scanner(System.in).nextLine();
		s.draw();
		//向上转型后,只能调用父类定义的通用成员
		//子类特有成员不能调用
		//s.length();
		//s对象的真实类型是 Line 类型
		if(s instanceof Line) {
    
			//向下转型成Line类型,才能调用它特有的方法
			Line line = (Line) s;
			line.length();
		}
		new Scanner(System.in).nextLine();
		s.clear();
	}
}

练习题:面向对象 设计士兵类

需求:设计士兵与武器AK47类,并完成前进、进攻、发射子弹、装载子弹的功能

士兵类:
package cn.cxy.exec;
/*
 * 封装:
 *     士兵相关的属性数据、逻辑运算方法,
 *     封装成一个士兵“类”组件
 */
import java.util.Random;
public class Soldier {
    
	//成员变量,属性变量
	int id; //默认值0
	int blood = 100;
	AK47 a;//默认 null 值

	//成员方法
	public void go() {
    
		//this是一个特殊引用
		//引用“当前对象”的地址
		//当前对象:谁调用就是谁
		//可以省略,缺省存在
		System.out.println(this.id+"号士兵前进");
	}

	public void attack() {
    
		if(blood == 0) {
    
			System.out.println("这是"+id+"号士兵的尸体");
			return;//方法结束
		}
		System.out.println(id+"号士兵进攻");
		if(a != null) {
    
			a.fire();//调用枪发射子弹
		}
		//模拟进攻掉血
		//随机的减血量
		int d = new Random().nextInt(10);
		blood -= d;    
		if(blood < 0) {
    //不允许负数血量
			blood = 0;
		}
		System.out.println("血量:"+blood);
		//血量是0
		if(blood == 0) {
    
			System.out.println(id+"号士兵阵亡");
		}
	}
}
武器类:
package cn.cxy.exec;
import java.util.Random;
/*
 * 封装:
 *     AK47武器相关的属性数据、运算代码,
 *     封装成一个“类”组件
 */
public class AK47 {
    
	int bullets = 100;
	public void fire() {
    
		if(bullets == 0) {
    
			System.out.println("没有子弹");
			return;
		}
		//随机产生发射子弹数量
		int r = new Random().nextInt(10);
		//要发射的数量,比现有子弹多
		if(r > bullets) {
    
			r = bullets;//有多少发多少
		}
		bullets -= r;
		for(int i=0;i<r;i++) {
    
			System.out.print("突");
		}
		System.out.println("~");
		if(bullets == 0) {
    
			System.out.println("弹夹空了");
		}
	}

	public void load() {
    
		bullets = 100;
		System.out.println("弹夹已装满");
	}
}
测试类1:
package cn.cxy.exec;

public class Test1 {
    
	public static void main(String[] args) {
    
		//新建 Soldier 士兵对象
		//内存地址,保存到变量s1
		Soldier s1 = new Soldier();
		Soldier s2 = new Soldier();
		//用s1引用第一个士兵对象
		//为它的id赋值
		s1.id = 9527;
		s2.id = 9528;
		//用s1找到第一个士兵对象
		//让第一个士兵执行go()方法代码
		s1.go();
		s2.go();
		//新建 AK47 对象,保存到s1.a
		s1.a = new AK47();
		s2.a = new AK47();
		s2.attack();
		s2.attack();
		s2.attack();
		s2.attack();
	}
}

测试类2:
package cn.cxy.exec;

import java.util.Scanner;

public class Test2 {
    
	public static void main(String[] args) {
    
		//新建AK47对象,地址存到变量a
		AK47 a = new AK47();
		System.out.println("按回车射击,输入load装载子弹");
		while(true) {
    
			String s = new Scanner(System.in).nextLine();
			if(s.equals("load")) {
    
				a.load();
				continue;
			}
			a.fire();
		}
	}
}

练习题:面向对象 设计宠物类

需求:设计宠物类,用户可以自由选择养猫还是养狗,可以给宠物起名字,还可以实现喂食互动的功能,宠物需要有饱食度和快乐度

宠物类【父类】:
package cn.cxy.exec;
public class Pet {
    
	String name;
	int full;
	int happy;
	public Pet(String name) {
    
		this(name, 50, 50);
	}
	public Pet(String name,int full,int happy) {
     
		this.name = name;
		this.full = full;
		this.happy = happy;
	}
	public void feed() {
    //宠物的喂食方法
		if(full == 100) {
    
			System.out.println(name+"已经吃饱了");
			return;
		}
		System.out.println("给"+name+"喂食");
		full += 10;
		System.out.println("饱食度:"+full);
	}
	public void play() {
    //宠物的互动玩耍方法
		if(full == 0) {
    
			System.out.println(name+"已经饿得玩不动了");
			return;
		}
		System.out.println("陪"+name+"玩耍");
		happy += 10;
		full -= 10;
		System.out.println("快乐度:"+happy);
		System.out.println("饱食度:"+full);
	}
	public void punish() {
    //宠物的惩罚方法
		//子类不同的代码,改成调方法
		System.out.println(
				"打"+name+"的pp,"+name+"哭叫:"+cry());
		happy -= 10;
		System.out.println("快乐度:"+happy);
	}
	public String cry() {
    //小动物被打哭了
		//无意义代码
		//cry()方法需要在子类中重写,返回具体哭叫声
		return "此处有哭叫声";
	}
}
小猫类【子类】:
package cn.cxy.exec;
public class Cat extends Pet{
    
	public Cat(String name, int full, int happy) {
    
		super(name, full, happy);
	}
	public Cat(String name) {
    
		super(name);
	}
	@Override
	public String cry() {
    
		return "喵~";
	}
}
小狗类【子类】:
package cn.cxy.exec;
public class Dog extends Pet {
    
	public Dog(String name, int full, int happy) {
    
		super(name, full, happy);
	}
	public Dog(String name) {
    
		super(name);
	}
	@Override
	public String cry() {
    
		return "汪~";
	}
}
测试类:
package cn.cxy.exec;

import java.util.Random;
import java.util.Scanner;

public class TestPet {
    
	public static void main(String[] args) {
    
		System.out.println("1. 狗");
		System.out.println("2. 猫");
		System.out.print("选择:> ");
		int c = new Scanner(System.in).nextInt();
		System.out.print("给宠物起个名字:");
		String n = new Scanner(System.in).nextLine();
		//定义猫狗变量
		Dog dog = null;
		Cat cat = null;
		if(c == 1) {
    
			dog = new Dog(n);
			play(dog);
		} else {
    
			cat = new Cat(n);
			play(cat);
		}
	}
	private static void play(Dog dog) {
    
		System.out.println("按回车执行");
		while(true) {
    
			new Scanner(System.in).nextLine();
			int r = new Random().nextInt(6);
			switch(r) {
    
			case 0: dog.feed(); break;
			case 1: dog.play(); break;
			default: dog.punish(); break;
			}
		}
	}
	private static void play(Cat cat) {
    
		System.out.println("按回车执行");
		while(true) {
    
			new Scanner(System.in).nextLine();
			int r = new Random().nextInt(6);
			switch(r) {
    
			case 0: cat.feed(); break;
			case 1: cat.play(); break;
			default: cat.punish(); break;
			}
		}
	}
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_43884234/article/details/116569562

智能推荐

while循环&CPU占用率高问题深入分析与解决方案_main函数使用while(1)循环cpu占用99-程序员宅基地

文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。​​​​​​while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99

【无标题】jetbrains idea shift f6不生效_idea shift +f6快捷键不生效-程序员宅基地

文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效

node.js学习笔记之Node中的核心模块_node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是-程序员宅基地

文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是

数学建模【SPSS 下载-安装、方差分析与回归分析的SPSS实现(软件概述、方差分析、回归分析)】_化工数学模型数据回归软件-程序员宅基地

文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件

利用hutool实现邮件发送功能_hutool发送邮件-程序员宅基地

文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件

docker安装elasticsearch,elasticsearch-head,kibana,ik分词器_docker安装kibana连接elasticsearch并且elasticsearch有密码-程序员宅基地

文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码

随便推点

Python 攻克移动开发失败!_beeware-程序员宅基地

文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware

Swift4.0_Timer 的基本使用_swift timer 暂停-程序员宅基地

文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停

元素三大等待-程序员宅基地

文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待

Java软件工程师职位分析_java岗位分析-程序员宅基地

文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析

Java:Unreachable code的解决方法_java unreachable code-程序员宅基地

文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code

标签data-*自定义属性值和根据data属性值查找对应标签_如何根据data-*属性获取对应的标签对象-程序员宅基地

文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象

推荐文章

热门文章

相关标签