Notes on Java from introduction to mastery

Special course (comprehensive case)

Programming thinking training

1. Programming thinking

The ability to use the learned Java technology to solve problems and write code

2. Suggestions on improving programming thinking and programming ability

Programming thinking and programming ability are not formed overnight. It takes time to precipitate and a lot of practice

Specific measures:

Diligent in practicing code, diligent in thinking, who can make perfect
Early stage: imitate first, later stage: innovate again

A small step makes a thousand miles; If you don't accumulate small streams, you can't form rivers and seas.

Case 1: buying air tickets

Requirements:

The ticket price is charged according to the off-season and peak season, first-class and economy class. Enter the original ticket price, month and first-class or economy class
Calculate the ticket price according to the following rules:
10% off for first class and 8.5% off for economy class in peak season (may October)
7% off for first class and 6.5% off for economy class in the off-season (November to April)

analysis:

1. Define a method to enter the original ticket price, month and cabin type
2. Use if to judge whether the month is the peak season or the off-season, and use the switch branch to judge whether it is first class or economy class
3. Select the corresponding discount to calculate and return the calculation result

package com.itheima.type;

import java.util.Scanner;

public class TypeDemo1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the original ticket price:");
        double price = sc.nextDouble();
        System.out.println("Please enter the ticket month:");
        int month = sc.nextInt();
        System.out.println("Please enter the cabin to which the ticket belongs:");
        String type = sc.next();
        double rs = calc(price, month, type);
        System.out.println("Your current ticket price is:" + rs);
    }
    public static double calc(double price, int month, String type) {
        if(month >= 5 && month <= 10) {
            switch (type){
                case "First class":
                    price *= 0.9;
                    break;
                case "economy class":
                    price *= 0.85;
                    break;
                default:
                     System.out.println("The class you entered is incorrect~~~");
                     price = -1;
            }
        }else if(month == 11 || month == 12 || month >= 1 && month <= 4){
            switch (type){
                case "First class":
                    price *= 0.7;
                    break;
                case "economy class":
                    price *= 0.65;
                    break;
            }
        }else {
            System.out.println("There is a problem with the month you entered~~~");
            price = -1;
        }
        return price;
    }
}

Case 2: finding prime numbers

Requirements:

explain:

Prime: if it cannot be divided by other positive integers except 1 and itself, it is called prime

analysis:

1. The data between 101-200 can be obtained in turn by cycle
2. Every time you get a number, judge whether the number is a prime number
3. Start from 2 and traverse to half the data of the number to see if there is any data that can divide it. If there is, it is not a prime number and if there is no, it is a prime number

package com.itheima.type;

import java.util.Scanner;

public class TypeDemo1 {
    public static void main(String[] args) {
        prime();
    }
    public static void prime() {
        int count = 0;
        System.out.print("101-200 Prime between:");
        for (int i = 101; i <= 200; 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");
                count++;
            }
        }
        System.out.println();
        System.out.println("101-200 The number of prime numbers between is:" + count);
    }
}

Case 3: development verification code

Requirements:

Define a method to randomly generate a 5-digit verification code, each of which may be a number, uppercase letter and lowercase letter

analysis:

1. Define a method to generate a verification code return: the method parameter is the number of digits and the return value type of the method is String
2. Use the for loop inside the method to generate random characters with specified digits and connect them
3. Return the connected random characters as a set of verification codes

package com.itheima.type;

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

public class TypeDemo1 {
    public static void main(String[] args) {
        String code = createCode(5);
        System.out.println("The randomly generated verification code is:" + code);
    }
    public static String createCode(int n) {
        String code = "";
        Random r = new Random();
        for (int i = 0; i < n; i++) {
            int type = r.nextInt(3);
            switch (type) {
                case 0:
                    //capital
                    char ch1 = (char)(r.nextInt(26) + 65);
                    code += ch1;
                    break;
                case 1:
                    //capital
                    char ch2 = (char)(r.nextInt(26) + 97);
                    code += ch2;
                    break;
                case 2:
                    //number
                    code += r.nextInt(10);
                    break;
            }
        }
        return code;
    }
}

Case 4: copying array elements

Requirements:

Copy the elements from one array to another new array

analysis:

1. You need to dynamically initialize an array with the same length as the original array
2. Traverse each element of the original array and assign values to the new array in turn
3. Output the contents of two arrays

package com.itheima.type;

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

public class TypeDemo1 {
   public static void main(String[] args) {
       int[] arr1 = {11, 22, 33, 44};
       int[] arr2 = new int[arr1.length];
       copy(arr1, arr2);
       printArray(arr1);
       printArray(arr2);
   }
   public static void printArray(int[] arr) {
       System.out.print("[");
       for (int i = 0; i < arr.length; i++) {
           System.out.print(i == arr.length - 1 ? arr[i] : arr[i] + ", ");
       }
       System.out.println("]");
   }
   public static void copy(int[] arr1, int[] arr2) {
       for (int i = 0; i < arr1.length; i++) {
           arr2[i] = arr1[i];
       }
   }
}

Case 5: scoring by judges

Requirements:

In the singing competition, six judges give the contestants scores, and the score range is an integer between [0 - 100].
The final score of the contestant is the average score of the four judges after removing the highest score and the lowest score,
Please complete the above process and calculate the score of the contestant.

analysis:

1. Enter the scores of 6 judges into the program ---- > use array
2. Traverse each data in the array, accumulate and sum, and find the highest score and lowest score
3. Calculate the average score according to the calculation rules of the score

package com.itheima.type;

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

public class TypeDemo1 {
    public static void main(String[] args) {
        int[] scores = new int[6];
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < scores.length; i++) {
            System.out.print("Please enter page" + (i + 1) + "Scoring of judges:");
            scores[i] = sc.nextInt();
        }
        int max = scores[0];
        int min = scores[0];
        int sum = scores[0];
        for (int i = 1; i < scores.length; i++) {
            if(min > scores[i]){
                min = scores[i];
            }
            if(max <scores[i]){
                max = scores[i];
            }
            sum += scores[i];
        }
        System.out.println("The highest score is:" + max);
        System.out.println("The minimum score is:" + min);
        double res = (sum - max - min) * 1.0 / (scores.length - 2);
        System.out.println("The final average score of the contestant is:" + res);
    }
}

Case 6: digital encryption

Requirements:

The digital password of a system, such as 1983, is transmitted by encryption,
The rule is as follows: first get each digit, then add 5 to each number, then find the remainder of 10, and finally reverse all numbers to get a new string of numbers.

analysis:

1. Store each data into the array, traverse the array, change each data according to the rules, and store the changed data into the array again
2. Exchange the front and back elements of the array, and the final element in the array is the result of encryption

package com.itheima.type;

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

public class TypeDemo1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Please enter the number of numbers to be encrypted:");
        int length = sc.nextInt();
        int[] arr1 = new int[length];
        for (int i = 0; i < arr1.length; i++) {
            System.out.print("Please enter page" + (i + 1) + "Digital password:");
            arr1[i] = sc.nextInt();
        }
        System.out.println("The encrypted password is:" + enCode(length, arr1));
    }
    public static int enCode(int length, int[] arr1){
        for (int i = 0; i < arr1.length; i++) {
            arr1[i] = (arr1[i] + 5) % 10;
        }
        int temp;
        for (int i = 0, j = arr1.length - 1; i < j; i++, j--) {
            temp = arr1[i];
            arr1[i] = arr1[j];
            arr1[j] = temp;
        }
        int res = arr1[3] + arr1[2] * 10 + arr1[1] * 100 + arr1[0] * 1000;
        return res;
    }
}

Case 7: grab red envelopes

Requirements:

A big V live lottery, the prize is a cash red envelope, with {2, 588, 888, 1000, 10000} five bonuses respectively.
Please use the code to simulate the lottery and print out each award. The order of awards should be random and not repeated.
The printing effect is as follows: (random order, not necessarily the following order)
The bonus of 888 yuan was withdrawn
A bonus of 588 yuan was withdrawn
The 10000 yuan bonus was withdrawn
A bonus of 1000 yuan was withdrawn
A bonus of 2 yuan was withdrawn

analysis:

1. Define an array of these bonuses
2. Define an array to record the amount that has been drawn.
3. Each lottery draws a random index, takes out the bonus amount corresponding to the index, judges whether the amount has been drawn before, and draws it again

package com.itheima.type;

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

public class TypeDemo1 {
    public static void main(String[] args) {
        int[] redPacket = {2, 588, 888, 1000, 10000};
        boolean[] redPacketStatus = new boolean[redPacket.length];
        for (int i = 0; i < redPacketStatus.length; i++) {
            redPacketStatus[i] = true;
        }
        Random r = new Random();
        int i = 0;
        while (true){
            int money = r.nextInt(redPacket.length);
            if(redPacketStatus[money]){
                System.out.println(redPacket[money] + "The bonus of yuan was drawn out");
                i++;
            }
            redPacketStatus[money] = false;
            if(i == redPacket.length) break;
        }
    }
}

Case 8: simulated two-color ball [expansion]

Analysis of a random group of winning numbers:

1. The winning number consists of 6 red balls and 1 basketball (Note: the requirements for 6 red balls cannot be repeated)
2. You can define a method to return a set of winning numbers (7 data) in the form of an integer array

The user enters a set of two-color ball number analysis:

1. Define a method that can enter 6 red balls and 1 basketball number entered by the user
2. This method finally needs to return an array, which is the number entered by the user (7 digits)

Analysis of winning judgment

1. Define a method that can receive an array of winning numbers and an array of user selected numbers
2. Judge the final winning situation according to the number of hit red balls and basketball, and output the details and winning amount

package com.itheima.type;

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

public class TypeDemo1 {
    public static void main(String[] args) {
        int[] luckNumbers = createLuckNumbers();
        
        int[] userNumbers = userInputNumbers();

        judge(luckNumbers, userNumbers);
    }
    //Print array
    public static void printArry(int[] arr){
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(i == arr.length - 1 ? arr[i] : arr[i] + "\t");
        }
        System.out.println("]");
    }
    //Randomly generate winning numbers
    public static int[] createLuckNumbers(){
        int[] numbers = new int[7];
        boolean[] numbersStatus1 = new boolean[33];
        for (int i = 0; i < numbersStatus1.length; i++) {
            numbersStatus1[i] = true;
        }
        Random r = new Random();
        int i = 0;
        while(true){
            int num1 = r.nextInt(33) + 1;
            if(numbersStatus1[num1 - 1]){
                numbers[i] = num1;
                numbersStatus1[num1 - 1] = false;
                i++;
            }
            if(i == numbers.length - 1) break;
        }
        numbers[numbers.length - 1] = r.nextInt(16) + 1;
        return numbers;
    }
    //Enter user number
    public static int[] userInputNumbers(){
        int[] numbers = new int[7];
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < numbers.length - 1; i++) {
            System.out.print("Please enter the number" + (i + 1) + "Number(In 1-33 And the number cannot be repeated): ");
            numbers[i] = sc.nextInt();
        }
        System.out.print("Please enter the 7th number(In 1-16 between): ");
        numbers[6] = sc.nextInt();
        return  numbers;
    }
    //Judge whether the user wins the prize
    public static void judge(int[] luckNumbers, int [] userNumbers){
        int redHitNumbers = 0;
        for (int i1 = 0; i1 < userNumbers.length - 1; i1++) {
            for (int i = 0; i < luckNumbers.length - 1; i++) {
                if(luckNumbers[i] == userNumbers[i1]){
                    redHitNumbers++;
                    break;
                }
            }
        }
        int blueHitNumbers = userNumbers[6] == luckNumbers[6] ? 1 : 0;

        System.out.println("The winning number is:");
        printArry(luckNumbers);
        System.out.println("Your bet number is:");
        printArry(userNumbers);
        System.out.println("You hit" + redHitNumbers + "A red ball");
        System.out.println("You hit" + blueHitNumbers + "A basketball");

        if(blueHitNumbers == 1 && redHitNumbers < 3)
            System.out.println("Congratulations, you won the 5 yuan prize!");
        else if(blueHitNumbers == 1 && redHitNumbers == 3
        || blueHitNumbers ==0 && redHitNumbers == 4)
            System.out.println("Congratulations, you won the 10 yuan prize!");
        else if(blueHitNumbers == 1 && redHitNumbers == 4
                || blueHitNumbers ==0 && redHitNumbers == 5)
            System.out.println("Congratulations, you won 200 yuan!");
        else if(blueHitNumbers == 1 && redHitNumbers == 5)
            System.out.println("Congratulations on winning the 3000 yuan prize!");
        else if(blueHitNumbers == 0 && redHitNumbers == 6)
            System.out.println("Congratulations on winning the 5 million super prize!");
        else if(blueHitNumbers == 1 && redHitNumbers == 6)
            System.out.println("Congratulations on winning 10 million! Can begin to enjoy life, poetry and distance!!");
        else System.out.println("Thank you for your outstanding contribution to welfare!!");

    };
}

Keywords: Java Back-end

Added by MnilinM on Sat, 12 Feb 2022 00:58:10 +0200