Rookie learning Java case

demo1: ticket pricing

Case: When a user buys an air ticket, the original price of the air ticket will be discounted according to the low season, peak season, first class or economy class. The preferential plan is as follows: May to October is the peak season, 10% off first class, 15% off economy class, November April next year is the off-season, with 30% discount for first class and 35% discount for economy class. Please develop a program to calculate the preferential price of the user's current air ticket.

package it.heima.cesahihaha;

public class demo1 {
    
    
    public static void main(String[] args) {
    
    
        double price = count(10, 1000, "经济舱");
        System.out.println("折后价:" + price);
    }
    public  static double count(int month, double price, String type){
    
    
        //判断是单击还是旺季
        // 分别判断舱位并计算价格

        if(month <= 10 && month >=5 ){
    
    
            switch (type) {
    
    
                case "经济舱" :
                    price *= 0.5;
                    break;
                case "头等舱" : price *= 0.7;
            }
        }else{
    
    
            switch (type) {
    
    
                case "经济舱" :
                    price *= 0.9;
                    break;
                case "头等舱" :
                    price *= 0.8;
                    break;
            }
        }

        return price;
    }
}

demo2: Generate random numbers

insert image description here

package it.heima.cesahihaha;

import java.util.Random;

public class demo1 {
    
    
    public static void main(String[] args) {
    
    
        String code = coding(5);
        System.out.println(code);
    }

    public static String coding(int n){
    
    
        String codes = "";
        for (int i = 0; i < n; i++) {
    
    
            Random random = new Random();
            int r = random.nextInt(3);
            switch(r){
    
    
                case 0:
                    int c = random.nextInt(9);
                    codes += c;
                    break;
                case 1:
                    int d = random.nextInt(25) + 65;
                    codes += (char)d;
                    break;
                case 2:
                    int e= random.nextInt(25) + 97;
                    codes += (char)e;
                    break;
            }

        }
        return codes;
    }
}

demo3: Judges scoring case

Requirements: In a singing competition, there may be multiple judges who want to score the contestants, and the scores are integers between [0 - 100]. The final score of the contestants is: the average score of the remaining scores after removing the highest score and the lowest score. Please write a program that can enter the scores of multiple judges and calculate the final score of the contestants

package it.heima.cesahihaha;

import com.sun.istack.internal.NotNull;

import java.util.Scanner;

public class demo1 {
    
    
    public static void main(String[] args) {
    
    

        // 获取人数
        // 传入方法,计算平均分数
        // 打印分数

        double[] score = scorefunction(6);
        System.out.println("去掉一个最高分:"+ score[1] + "去掉一个最低分:"+ score[2] + "最后平均分:"+score[0]);
    }

    
    public static double[] scorefunction(@NotNull int n){
    
    

        // 遍历n次获取输入分数
        // 根据每次输入分数,找出极值
        // 全部输入求和,减去极值,计算平均
        // 返回分数
        Scanner scanner = new Scanner(System.in);
        double max = 0.;
        double min = 0.;
        double scoreavg = 0.0;
        
        for (int i = 0; i < n; i++) {
    
    
            double input = scanner.nextDouble();
            if(i==0){
    
    
                max = input;
                min = input;
            }
            if(input > max){
    
    
                max = input;
            }
            if (input < min){
    
    
                min = input;
            }
            scoreavg += input;
        }
        scoreavg -= (min+max);
        scoreavg = scoreavg/(n-2);

        double[] values = new double[3];
        values[0] = scoreavg;
        values[1] = max;
        values[2] = min;
        return values;
    }
}

What does @NotNull in front of the java method do and how does it work?

In Java, @NotNull is a tag used to annotate method parameters, fields or return values. It is used to indicate that an element (parameter, field or return value) cannot be null. The purpose of this annotation is to improve the reliability and readability of the code, and reduce potential null pointer exceptions by making it clear that an element cannot be null.

The @NotNull annotation itself does not change the behavior of the code or actually perform any runtime checks. It is just metadata used to provide additional information to development tools, static analyzers or other related tools. These tools can read these annotations and perform validation, warning, or error reporting as required by the annotations.

For example, when using a parameter annotated with @NotNull, the development tools can statically analyze the code and check whether it is possible to pass a null value to the parameter. If potential problems are found, development tools can issue warnings or errors to help developers find problems early.

Here is a sample code that demonstrates how to use the @NotNull annotation

public class Example {
    
    
    public void processUser(@NotNull String userName) {
    
    
        // 方法体省略
    }
}

In the above code, the userName parameter of the processUser method is marked @NotNull, which means that the parameter cannot be null. The development tool can verify whether the method call complies with this requirement based on this annotation.

Please note that the @NotNull annotation is not a native annotation of the Java language, it is usually provided by a third-party library or framework. In practice, you need to use a tool or library that supports this annotation, and make sure that the corresponding checks are enabled during build and analysis.

demo4: digital encryption

insert image description here

package it.heima.cesahihaha;


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

public class demo1 {
    
    
    public static void main(String[] args) {
    
    
        // 获取一个数字a
        // 传给加密程序f
        // 输出加密后的数字b
        // 对数字b进行解密得到结果c
        // 输出ac是否相等

        Scanner scanner = new Scanner(System.in);
        System.out.println("输入原码:");

        while(true) {
    
    
            int sc = scanner.nextInt();
            if (sc < 0) {
    
    
                System.out.println("请输入大于0的数字:");
            }else{
    
    
                int[] b = jiami(sc);
                System.out.println("密文:" + Arrays.toString(b));
                int[] c = jiemi(b);
                System.out.println("解码:" + Arrays.toString(c));
                juge(sc, c);
                break;
            }
        }



    }

    public static int[] jiami(int a){
    
    
        // 输入数字a
        // 加密
        //输出加密后的数字b

        int[] list = number2list(a);
        System.out.println("原码转成数组 :"+Arrays.toString(list));
        int index = list.length;
//        System.out.println("length: " + index);
        int[] reverlist = new int[index];

        for (int i = 0; i < index; i++) {
    
    
            reverlist[index-1-i] = jia(list[i]);
        }

        return reverlist;
    }
//    public static int list2number(int[] list){
    
    
//        int len = list.length;
//        int chen = 1;
//        int sum = 0;
//        for (int i = 0; i < len; i++) {
    
    
//            sum += list[len-1-i] * chen;
//            chen *= 10;
//        }
//        return sum;
//    }

    public static int[] number2list(int a){
    
    
        // 判断数字长度
        int index = 1;
        int chushu = 1;
        while(true){
    
    
            chushu *= 10;
            index += 1;
            if ((a / chushu)<10){
    
    
                break;
            }
        }
        System.out.println("长度:"+index);
        // 数组存值
        int[] list = new int[index];

        for (int i = 0; i < index ; i++) {
    
    
            int a1 = a % 10;
            list[index-1-i] = a1;
            a /= 10;
        }
        return list;
    }

    public static int jia(int e){
    
    
        return (e + 5) %10;
    }

    public static int jie(int e){
    
    
        if (e > 4){
    
    
            return e-5;
        }else{
    
    
            return e+10-5;
        }
    }

    public static int[] jiemi(int[] b){
    
    
        // 输入数字b
        // 解密
        // 输出解密数字c
        int[] list = b;
        int len = list.length;
        int[] reverlist = new int[len];
        for (int i = 0; i < len; i++) {
    
    
            reverlist[len-1-i] = jie(list[i]);
        }
        return reverlist;
    }

    public static void juge(int a, int[] c){
    
    
        // 返回布尔
        int[] t0 = number2list(a);
        System.out.println("判断时c数组 :"+Arrays.toString(c));
        for (int i = 0; i < t0.length; i++) {
    
    
            if (t0[i] != c[i]){
    
    
                System.out.println("决策:" + false);
                return;
            }
        }
        System.out.println("决策:" + true);
    }
}


test

输入原码:
1234567890
长度:10
原码转成数组 :[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
密文:[5, 4, 3, 2, 1, 0, 9, 8, 7, 6]
解码:[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
长度:10
判断时c数组 :[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
决策:true

There are also some loopholes in the above code, guys, study it yourself!

Introduction to split usage in java
In Java, split() is a method for string splitting. It takes a regular expression as an argument and splits the string into an array of strings.

Following is the syntax of the split() method −

public String[] split(String regex)

Parameter Description:

regex: Indicates the regular expression used to split the string.
return value:

String[]: An array containing the split substrings.
Example usage:

String str = "Hello,World,Java";
String[] parts = str.split(","); // 使用逗号作为分割符

In the above example, the original string "Hello, World, Java" is split by the split(",") method using a comma as the separator, and will be split into an array containing three substrings: ["Hello", "World", "Java"].

Precautions:

The argument in the split() method can be any legal regular expression. For example, if you want to use a period as a separator, you can use "." as a parameter.
If there are special characters in the regular expression, you need to use double slashes "\" to escape. For example, if you want to use a slash as a separator, you can use "\" as a parameter.
If you want to limit the number of splits, you can use the split() method with a limit number parameter. For example, use split(",", 2) to split a string into two parts instead of multiple substrings.
This is a brief introduction and usage of the split() method in Java. Use the split() method to easily split the string according to the specified separator and get a string array.

How to convert String "1" to int 1?

To convert the string "1" to the integer 1, use the static method parseInt() of the Integer class.

Here is a sample code:

String str = "1";
int num = Integer.parseInt(str);

In the above code, we use Integer.parseInt(str) to convert the string str into a variable num of integer type.

Need to pay attention to the following points:

If the string cannot be parsed as a valid integer, such as "abc", a NumberFormatException will be thrown. So it's a good idea to make sure the string can be successfully parsed as an integer before doing the conversion.
If the value represented by the string exceeds the range of the integer, a NumberFormatException will also be thrown. For example, if the character string is "2147483648", it exceeds the maximum value of 2147483647 for the int type.
If you want to handle exceptions during conversion, you can use a try-catch block to catch NumberFormatException exceptions.

String str = "abc";
try {
    
    
    int num = Integer.parseInt(str);
    System.out.println(num);
} catch (NumberFormatException e) {
    
    
    System.out.println("无法解析字符串为整数。");
}

The above code will output "Cannot parse string as an integer." when the string cannot be parsed as an integer.

To summarize, to convert the string "1" to the integer 1, you can use the Integer.parseInt() method.


Hey, the previous demo4 vulnerability correction is: you should customize number2string, string2number for conversion...

Guess you like

Origin blog.csdn.net/AdamCY888/article/details/131458730