阐明

本大节为Java根底语法练习环节,利用前几大节解说过的内容进行练习,达到坚固的目标。

买飞机票

public static void main(String[] args) {    double price = calcDiscount(1000, 8, "经济舱");    System.out.println(price);}public static double calcDiscount(double price, int month, String type) {    // 判断月份    if (month >= 5 && month <= 10) {        // 淡季        switch(type) {            case "头等舱":                price *= 0.9;                break;            case "经济舱":                price *= 0.85;                break;        }    } else {        // 旺季        switch (type) {            case "头等舱":                price *= 0.7;                break;            case "经济舱":                price *= 0.65;                break;        }    }    return price;}

开发验证码

public static void main(String[] args) {    String code = getRandomNum(6);    System.out.println(code);}public static String getRandomNum(int n) {    Random r = new Random();    String code = "";    // 依据传递过去的位数来进行循环    for(int i=0;i<n;i++){        // 生成一个随机数 0-2之间,0 示意数字 1 大写字母 2 小写字母        int type = r.nextInt(3);        switch (type) {            case 0:                // 数字                code += r.nextInt(10); // 生成0-9随机数                break;            case 1:                // 大写字母 A 65 Z 65+ 25                char ch1 = (char)(r.nextInt(26) + 65);                code += ch1;                break;            case 2:                // 小写字母 a 97  z 97 + 25                char ch2 = (char) (r.nextInt(26) + 97);                code += ch2;                break;        }    }    return  code;}
Java中应用random包中的nextInt()办法生成指定范畴随机数公式: nextInt(max - min + 1) + min;

评委打分

public static void main(String[] args) {//        double[] list = { 10, 11, 12, 13,14 };//        System.out.println(Arrays.toString(getMaxAndMinVal(list)));    System.out.println(getAverage(4)); // 15.5}// 获取一个评分public static double getAverage(int n) { // n 示意评委人数    Scanner sc = new Scanner(System.in);    double[] scoreList = new double[n];    double sum = 0;    for(int i=0;i<n;i++){        System.out.println("请输出第" + (i+1) + "位分数:");        double score = sc.nextDouble();        scoreList[i] = score;        sum += score; // 将分数加到总分上    }    // 调用getMaxAndMinVal办法,获取最小值和最大值    double[] maxAndMinList = getMaxAndMinVal(scoreList);    // 计算分数    return (sum - maxAndMinList[0] - maxAndMinList[1]) / (n-2);}public static double[] getMaxAndMinVal(double[] list) {    double max = list[0];    double min = list[0];    for(int i=0;i<list.length;i++) {        if (list[i] > max) {            max = list[i];        }        if (list[i] < min) {            min= list[i];        }    }    return new double[]{ min, max };}