Java常见练习实验小程序

1. 闰年的判断 & 成绩等级判断
闰年判断:判断公式
    ① 4年一闰,百年不闰(即能被4整除,且不能被100整除)
    ② 400年再闰(即能被400整除)
成绩判断:成绩等级划分
    ① 成绩的合理性 🢂 高于最低分,低于最高分(一般 分数>0&分数<100)
    ② 等级划分(优秀,良好,合格,不及格)

🢆 代码演示 ▶⯈⮞

package test;

public class CodeTiny01 {
    public static void main(String[] args) {
        /*
        判断公式:
        ① 4年一闰,百年不闰(即能被4整除,且不能被100整除
        ② 400年再闰(即能被400整除)
        */
        int year = 2000;
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            System.out.println(year + "是闰年");
        } else {
            System.out.println(year + "是平年");
        }

        /*
        成绩等级判断
        ① 成绩的合理性 🢂 高于最低分,低于最高分(一般 分数>0&分数<100)
        ② 等级划分(优秀,良好,合格,不及格)
         */
        int score = 95;
        if (score < 0 || score > 100) {
            System.out.println("F-成绩不合法");
        } else if (score >= 90) {
            System.out.println("A-优秀");
        } else if (score >= 80) {
            System.out.println("B-良好");
        } else if (score >= 60) {
            System.out.println("C-合格");
        } else {
            System.out.println("D-不及格");
        }
    }
}
2. 数的正负零值 & 月份天数
正负零值:判断规则
    ① 正数打印 "+"
    ② 负数打印 "-"
    ③ 0 则打印 "0"
月份天数:成绩等级划分
    ① 1,3,5,7,8,10,12(一个月31天)
    ② 4,6,9,11(一个月30天)
    ③ 2(闰年29天,平年28天)

🢆 代码演示 ▶⯈⮞

package test;

import java.util.Scanner;

public class CodeTiny02 {
    public static void main(String[] args) {
        /*
        判断一个数的正负零值
        ① 正数打印 "+"
    	② 负数打印 "-"
    	③ 0 则打印 "0"
         */
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int num = scan.nextInt();
        if(num>0){
            System.out.println("+");
        }else if(num<0){
            System.out.println("-");
        }else{
            System.out.println("0");
        }


        /*
        更据年份year和月份month,计算该年该月的天数
        ① 1,3,5,7,8,10,12(一个月31天)
    	② 4,6,9,11(一个月30天)
    	③ 2(闰年29天,平年28天)
         */
        System.out.println("请输入年份:");
        int year = scan.nextInt();
        System.out.println("请输入月份:");
        int month = scan.nextInt();
        int days = 0;
        switch(month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                days = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                days = 30;
                break;
            case 2:
                if((year%4==0 && year%100!=0) || year%400==0){
                    days = 29;
                }else{
                    days = 28;
                }
        }
        System.out.println(year+"年的"+month+"月共"+days+"天");
    }
}
3. 随机算数题 & 乘法口诀表 & 随机数的最大值最小值
算术题:出题规则
    ① 1,2,3,4类分别为加,减,乘,除四类题目
    ② 除法计算时四舍五入保留一位小数
    ③ 每次随机10道题(手动输入数的最大范围)
乘法口诀:以正常乘法口诀表输出(下三角)
随机数的最大值最小值:随机生成10个数,求出最大值和最小值

🢆 代码演示 ▶⯈⮞

package test;

import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;

public class CodeTiny03 {
    public static void main(String[] args) {
        /*
         * 随机题
         */
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        // 随机运算出题
        int score = 0;
        System.out.print("请输入第一个数最大范围:");
        int num = scanner.nextInt();
        System.out.print("请输入第二个数最大范围:");
        int number = scanner.nextInt();
        // 错题统计
        int f = 1;
        // 四舍五入保留一位小数decimalFormat.format(number);
        DecimalFormat decimalFormat = new DecimalFormat("#.#");
        for (int a = 1; a <= number; a++) {
            double n = random.nextInt(num);
            // 0不作除数
            double m = random.nextInt(10) + 1;
            // 随机类型出题
            int types = random.nextInt(4) + 1;
            double result = 0.0;
            // 除法结果
            switch (types) {
                case 1:
                    System.out.printf("第%d题 题目:%s + %s = ?  ", a, decimalFormat.format(n), decimalFormat.format(m));
                    result = n + m;
                    break;
                case 2:
                    System.out.printf("第%d题 题目:%s - %s = ?  ", a, decimalFormat.format(n), decimalFormat.format(m));
                    result = n - m;
                    break;
                case 3:
                    System.out.printf("第%d题 题目:%s × %s = ?  ", a, decimalFormat.format(n), decimalFormat.format(m));
                    result = n * m;
                    break;
                case 4:
                    System.out.printf("第%d题 题目:%s ÷ %s = ?  ", a, decimalFormat.format(n), decimalFormat.format(m));
                    result = Double.parseDouble(decimalFormat.format((n / m)));
                    break;
            }
            System.out.print("请输入当前题目的答案:");
            double answer = scanner.nextDouble();
            if (result == answer) {
                System.out.println("恭喜你答对了!");
                score += 10;
                System.out.println("当前得分:" + score);
            } else {
                f += 1;
                System.out.println("哦!答错了哟,别灰心继续答下一个题");
                System.out.println("正确答案:" + result);
                System.out.println("f=" + f + "n=" + number);
                if (f > number) {
                    System.out.println("最后一题正确答案:" + result);
                    System.out.println("哦!竟然一个题都没答对");
                }
            }
        }
        System.out.println("本次得分:" + score);


        /*
         * 乘法口诀表
         */
        for (int x = 1; x <= 9; x++) {
            //控制行
            for (int i = 1; i <= x; i++) {
                //控制列,\t表示制表位,占8位
                System.out.print(i + "*" + x + "=" + i * x + "\t");
            }
            //换行功能
            System.out.println();
        }

        /*
         * 随机数的最大值,最小值
         */
        int[] arr = new int[10];
        for(int i=0;i<arr.length;i++){
            arr[i] = (int)(Math.random()*100);
            System.out.println(arr[i]);
        }
        int max = arr[0];
        int min = arr[0];
        for(int i=1;i<arr.length;i++){
            if(arr[i]>max){
                max = arr[i];
            }
            if(arr[i]<min){
                min = arr[i];
            }
        }
        System.out.println("最大值:"+max+",最小值:"+min);
    }
}
4. 猜数字 & 随机验证码 & 2~100的素数
猜数字:随机生成一个数(目标值),根据每次输入提示,猜出该数字
    ① 当输入的数大于目标值,则提示猜大了
    ② 当输入的数小于目标值,则提示猜小了,逐渐逼近目标值
验证码:模拟生成随机验证码
    ① 选择需要生成的验证码长度
    ② 随机生成大小写字母及数字组成的验证码
素数:只有0和1两个因数的数

🢆 代码演示 ▶⯈⮞

package test;

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

public class CodeTiny04 {
    private static final Random random = new Random();
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        // 猜数字
        guessNumber();

        // 验证码
        String code = verificationCode(6);
        System.out.println("生成的验证码:" + code);

        // 素数
        prime();
    }

    /**
     * =================================================================================================================
     * 案例:猜数字游戏
     * java:while(true)死循环,break
     */
    public static void guessNumber() {
        // 目标值
        int hide = random.nextInt(100) + 1;
        System.out.println("目标值:" + hide);
        // 正确值
        double num = 0.0;
        double sum;

        // 循环猜数
        while (true) {
            num += 1;
            System.out.println("请输入要猜的数:");
            int guess = scanner.nextInt();

            if (hide < guess) {
                System.out.println("猜大了哦!");
            } else if (hide > guess) {
                System.out.println("猜小了哦!");
            } else {
                sum = 1 / num;
                System.out.println("正确率:" + precent(sum, 1));
                System.out.println("恭喜你,猜对了哟!");
                break;
            }
        }
    }

    /**
     * 将浮点数转化为百分比字符串输出
     *
     * @param number 需要转化的浮点数
     * @param n      需要保留的小数位数
     * @return 转化后的字符串形式
     */
    public static String precent(double number, int n) {
        String pre = String.format("%." + n + "f%%", number * 100);
        return pre;
    }
    // =================================================================================================================


    /**
     * =================================================================================================================
     * 生成验证码:A~Z,a~z,0~9
     *
     * @param number 验证码长度
     * @return 验证码字符串
     */
    public static String verificationCode(int number) {
        // 储存验证码
        String code = "";
        // 字符数组
        char[] captchaChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
                'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
                'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
                'y', 'z'};
        for (int i = 0; i < number; i++) {
            // 生成随机下标
            int index = random.nextInt(captchaChars.length);
            // 验证码拼接
            code += captchaChars[index];
        }
        return code;
    }
    // =================================================================================================================


    /**
     * =================================================================================================================
     * 查找2~100之间的素数
     */
    public static void prime() {
        for (int i = 2; i <= 100; i++) {
            boolean flag = true;
            for (int j = 2; j < i / 2; j++) {
                if (i % j == 0) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                System.out.print(i + "\t");
            }
        }
    }
    // =================================================================================================================
}
5. 机票打折 & 评委打分
机票打折:机票在不同时段的打折力度不同(分淡季和旺季)
    ① 淡季:11月到次年4月(经济舱6折,商务舱65折,头等舱7折)
    ② 旺季:5月到10月(经济舱8折,商务舱85折,头等舱9折)
评委打分:多位评委给选手打分
    ① 最终得分:去掉一个最高分和最低分的平均分
    ② 分支语句 + 循环语句 + 数组 + 方法

🢆 代码演示 ▶⯈⮞

package test;

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

public class CodeTiny05 {
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        // 机票打折
        System.out.print("请输入机票原价(大于0):");
        double prince = scanner.nextInt();
        System.out.print("请输入月份(1~12):");
        int month = scanner.nextInt();
        System.out.print("请输入舱位类型(1:经济舱 2:商务舱 3:头等舱):");
        int type = scanner.nextInt();
        System.out.println("您的本次机票价格为:" + discount(prince, month, type));

        // 评委打分
        System.out.print("请选择本次大赛的评委数(评委数量不得低于3人也不能大于10人):");
        int n = scanner.nextInt();
        if (n >= 3 && n <= 10) {
            System.out.println("选手最终得分:" + avgScore(scoreArr(n)));
        } else {
            System.out.println("评委数量有误!");
        }
    }


    /**
     * =================================================================================================================
     * 打折计算
     *
     * @param prince 价格
     * @param month  月份
     * @param type   舱位
     * @return 打折后的价格
     */
    public static double discount(double prince, int month, int type) {
        // 数据验证
        boolean check = checkData(prince, month, type);
        double finalPrice = 0.0;
        if (check) {
            finalPrice = princes(prince, month, type);
        }
        return finalPrice;
    }


    /**
     * 验证输入的数据是否合法
     *
     * @param prince 价格数据
     * @param month  月份数据
     * @param type   类型数据(舱位)
     * @return 是否有效
     */
    public static boolean checkData(double prince, int month, int type) {
        boolean isValid = true;
        if (prince < 0) {
            System.out.println("您输入的价格有误!");
            isValid = false;
        }
        if (month <= 0 || month > 12) {
            System.out.println("您输入的月份有误!");
            isValid = false;
        }
        if (type < 0 || type > 3) {
            System.out.println("您输入的舱位类型有误!");
            isValid = false;
        }
        return isValid;
    }


    /**
     * 最终价格
     *
     * @param price 价格
     * @param month 月份
     * @param type  类型(舱位)
     * @return 最终价格
     */
    public static double princes(double price, int month, int type) {
        double finalPrice = 0.0;
        switch (type) {
            case 1:
                if (month >= 5 && month <= 10) {
                    finalPrice = price * 0.8;
                } else {
                    finalPrice = price * 0.6;
                }
                break;
            case 2:
                if (month >= 5 && month <= 10) {
                    finalPrice = price * 0.85;
                } else {
                    finalPrice = price * 0.65;
                }
                break;
            case 3:
                if (month >= 5 && month <= 10) {
                    finalPrice = price * 0.9;
                } else {
                    finalPrice = price * 0.7;
                }
                break;
            default:
                System.out.println("输入有误!");
                break;
        }
        return finalPrice;
    }
    // =================================================================================================================


    /**=================================================================================================================
     * 评委打分
     * @param num 评委人数
     * @return 评委打分的数组
     */
    public static double[] scoreArr(int num) {
        System.out.println("本次大赛评委数:" + num);
        // 存储分数
        double[] scores = new double[num];
        boolean flag = true;
        while (flag) {
            for (int i = 0; i < scores.length; i++) {
                System.out.println("请第" + (i + 1) + "个评委打分(1~10分):");
                double score = scanner.nextDouble();
                if (score >= 0.0 && score <= 10.0) {
                    scores[i] = score;
                } else {
                    System.out.println("请评委老师认真打分!");
                    flag = false;
                    i -= 1;
                }
            }
            break;
        }
        return scores;
    }

    /**
     * 平均得分
     * @param scores 输入数组分数
     * @return 最终得分
     */
    public static double avgScore(double[] scores) {
        double avg = 0.0;
        Arrays.sort(scores);
        // 不统计最低分和最高分
        for (int i = 1; i < scores.length - 1; i++) {
            avg += scores[i];
        }
        System.out.println(Arrays.toString(scores));
        return avg / (scores.length - 2);
    }
    // =================================================================================================================
}

在这里插入图片描述

6. 学生类Student & 汽车类Car
学生类Student:java面向对象的简单应用
    ① 学生类(属性:姓名,年龄,班级,学号)
    ② 测试类(对学生类的简单测试,访问成员变量方法等)
汽车类Car:java面向对象的简单应用
    ① 汽车类(品牌,颜色,价格)
    ② 测试类(对学生类的简单测试,访问成员变量方法等)

🢆 代码演示 ▶⯈⮞

package working;

// 测试类
public class Work06 {
    public static void main(String[] args) {
        // 利用无参构造方法创建类的对象(周瑜,陆游)
        Student zy = new Student();
        // 访问成员变量
        zy.name = "周瑜";
        zy.age = 24;
        zy.className = "2023001";
        zy.stuId = "20001";
        // 访问成员方法
        zy.study();
        zy.sayHi();
        zy.playWith("李白");

        // 利用有参构造创建对象
        Student ly = new Student("陆游", 25, "2023002", "20002");
        // 访问成员方法
        ly.study();
        ly.sayHi();
        ly.playWith("李白");
    }
}


// 创建Student类
class Student{
    // 成员变量
    String name;
    int age;
    String className;
    String stuId;

    // 无参构造方法
    Student() {}
    // 有参构造方法
    Student(String name, int age, String className, String stuId) {
        this.name = name;
        this.age = age;
        this.className = className;
        this.stuId = stuId;
    }

    // 成员方法
    void study() {
        // 成员方法调用成员变量时,默认在成员变量之前有this关键字(this.name)
        System.out.println(name + "在学习java编程语言");
    }

    void sayHi() {
        System.out.println("你好,我叫" + name + "今年" + age + "岁," + "在" + className + "班" + "学号为" + stuId);
    }

    // 有参数的成员方法
    void playWith(String anotherName){
        System.out.println(name + "和" + anotherName + "正在打篮球!");
    }
}
package working;

public class Work07 {
    public static void main(String[] args) {
        // 类的实例化
        Car ford = new Car();
        ford.brand = "福特";
        ford.color = "红色的";
        ford.price = 210000;

        ford.start();
        ford.run();
        ford.stop();

        Car mazda = new Car("马自达", "白色的", 190000);
        mazda.start();
        mazda.run();
        mazda.stop();
    }
}


class Car {
    // 成员变量
    String brand;
    String color;
    double price;

    // 无参构造
    Car() {
    }

    // 有参构造
    Car(String brand, String color, double price) {
        this.brand = brand;
        this.color = color;
        this.price = price;
    }

    // 成员方法
    void start() {
        System.out.println(brand + "汽车正在启动!");
    }

    void run() {
        System.out.println("价值" + price + "¥的" + color + brand + "开始加速了");
    }

    void stop(){
        System.out.println(brand + "终于停下来了");
    }
}
7. 后缀名截取 & 控制用户名输入 & 域名获取公式名 & 字符数组验证码

🢆 代码演示 ▶⯈⮞ 获取给定文件名中的后缀名部分

package work;

public class Work01 {
    public static void main(String[] args) {
        // 截取png字符串
        String logo = "logo.png";
        // 截取js字符串
        String jquery = "jquery.1.1.2.js";
        System.out.println("截取后的字符串:" + getExtByName(logo));
        System.out.println("截取后的字符串:" + getExtByName(jquery));
    }
    /**
     * 获取给定文件名中的后缀名部分
     * @param name	文件名
     * @return 返回截取的字符串
     */
    public static String getExtByName(String name) {
        int start = name.lastIndexOf(".") + 1;
        int end = name.length();
        return name.substring(start, end);
    }
}

🢆 代码演示 ▶⯈⮞ 用户在控制台输入自己的用户名,然后验证

package work;

import java.util.Scanner;

/**
 * 要求用户在控制台输入自己的用户名。
 * 然后要求做如下验证工作:
 * 1:用户名不能为空(只要有一个字符)
 * 2:用户名必须在20个字以内
 * @author LongYongchuan
 */
public class Work02 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入名字:");
        System.out.println(getName(scanner.nextLine()));
    }

    /**
     * 判断用户输入的名字是否合法
     * @param name 输入的名字
     * @return 合法的名字
     */
    public static String getName(String name) {
        // 防止空格字符,现将空格去除
        if (name == null || name.trim().isEmpty() || name.length() >= 20) {
            System.out.println("您输入的名字不符合规则");
            name = "";
        }
        return name;
    }
}

🢆 代码演示 ▶⯈⮞ 域名判断是百度(baidu)或其他(输出判断结果)

package work;

import java.util.Scanner;

/**
 * 用户输入一个网址,格式如: www.baidu.com
 * 根据域名判断是百度(baidu)或其他(输出判断结果)
 * @author LongYongchuan
 */
public class Work05 {
    public static void main(String[] args) {
        System.out.print("请输入一个网址:");
        Scanner scanner = new Scanner(System.in);
        String line = scanner.nextLine();
        System.out.println("您输入的网址:" + line);
        //截取域名
        int start = line.indexOf(".") + 1;
        int end = line.indexOf(".", start);
        String name = line.substring(start, end);
        System.out.println(start + name + end);
        //判断域名
        if ("baidu".equals(name) {
            System.out.println("这是百度网站");
        } else {
            System.out.println("这是其他网站");
        }
    }
}

🢆 代码演示 ▶⯈⮞ 验证码的验证

package work;


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

/**
 * 生成一个4位验证码(数字和字母的组合)
 * 输出到控制台并提示用户输入该验证码(让用户输入,忽略大小写)
 * 输出:验证码正确,否则输出:验证码错误
 * @author LongYongchuan
 */
public class Work06 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String codes = code(6);
        System.out.println("本次验证码:" + codes);
        System.out.print("请输入验证码:");
        if (codes.equalsIgnoreCase(scanner.nextLine())){
            System.out.println("验证码正确");
        }else {
            System.out.println("验证码错误");
        }
    }

    /**
     * 随机生成验证码
     * @param n 验证码的长度
     * @return 随机验证码
     */
    public static String code(int n){
        Random random = new Random();
        String codes = "";
        String line = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        for (int i = 0; i < n; i++) {
            char c = line.charAt(random.nextInt(line.length() + 1));
            codes += c;
        }
        return codes;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一半不眠次日si记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值