Initial review-1

Posted by TheDumbNerd on Sat, 19 Feb 2022 10:44:53 +0100

Initial review

Process control

if -else

package Initial_practice;

import java.util.Scanner;

/*
Suppose you want to develop a lottery game. The program randomly generates a two digit lottery, prompts the user to enter a two digit lottery, and then determines whether the user can win according to the following rules.
1)If the number entered by the user matches the actual order of the lottery, the bonus is $10000.
2)If all the numbers entered by the user match all the numbers of the lottery, but the order is inconsistent, the bonus is $3000.
3)If the user enters a number that matches only one number of the lottery ticket in order, the bonus is $1000.
4)If a number entered by the user meets only one number matching the lottery ticket in non sequential case, the bonus is $500.
5)If there is no matching number entered by the user, the lottery will be cancelled.
 */
public class Test1 {
    // How to get a random number
    public static void main(String[] args) {
//        Math.random(); // [0.0-1.0] returns a double value and a positive sign, greater than or equal to 0.0 and less than 1.0. The return value and the selection are pseudo-random (about), and the range is evenly distributed.
//        int value =(int)(Math.random()*90+10);//[10.0-99]
//        //Formula [a,b]: (int)(Math.random*(b-a+1)+a)
//        System.out.println(value);
        int value =(int)(Math.random()*90+10);
        System.out.println("Please enter a two digit number: 10~99");
        Scanner scanner =new Scanner(System.in);
        int v_Td=value/10;
        int v_Sd=value%10;

        int num = scanner.nextInt();
        while(!(num>10&&num<99)){
            System.out.println("Please re-enter the number");
            num =scanner.nextInt();
        }
        int n_Td=num/10;
        int n_Sd=num%10;
        if(num==value){
            System.out.println("Congratulations on getting 10000 yuan bonus");
        }else if(v_Td==n_Sd&&v_Sd==n_Td){
            System.out.println("Congratulations on getting 3000 yuan bonus");
        }else if(v_Td==n_Td||v_Sd==n_Sd){
            System.out.println("Congratulations on getting a bonus of 1000 yuan");
        }else if(v_Td==n_Sd||v_Sd==n_Td){
            System.out.println("Congratulations on getting a 500 yuan bonus");
        }else{
            System.out.println("I'm sorry you didn't win the prize");
        }
        System.out.print("The winning number is:"+value);
    }
}

switch-case

package Initial_practice;

import java.util.Scanner;

/*
    Enter the year, month and day respectively from the keyboard to judge the day of the current year
    Note: the standard for judging whether a year is a leap year
        (1)It can be divided by 4, but not by 100
        (2)It can be divided by 400
 */
public class Test2 {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        System.out.println("Please enter the year you want to query");
        int year =scanner.nextInt();
        System.out.println("Please enter the month");
        int month =scanner.nextInt();
        System.out.println("Please enter the day number");
        int day = scanner.nextInt();
        int sumDay = 0;
        switch (month){
            case 12:
                sumDay+=30;
            case 11:
                sumDay+=31;
            case 10:
                sumDay+=30;
            case 9:
                sumDay+=31;
            case 8:
                sumDay+=31;
            case 7:
                sumDay+=30;
            case 6:
                sumDay+=31;
            case 5:
                sumDay+=30;
            case 4:
                sumDay+=31;
            case 3:
                if((year%4==0||year%400==0)&&year%100!=0){
                    sumDay+=29;
                }else{
                    sumDay+=28;
                }
                case 2:
                sumDay+=31;
            case 1:
                sumDay+=day;
                break;
        }
        System.out.print(year+"year"+month+"month"+day+"The first day of the year"+sumDay+"day");
    }
}

for

package Initial_practice;
import java.util.Scanner;
/*
   Enter two positive integers m and n to find their maximum common divisor and minimum common multiple
   The least common divisor of columns 12 and 20 is 4 and the least common multiple is 60
 */
public class Test3 {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        System.out.println("Please enter the first positive integer");
        int m = scanner.nextInt();
        System.out.println("Please enter the second positive integer");
        int n = scanner.nextInt();
        // Gets the smallest of the two numbers
        int min = Math.min(m,n);
        for (int i = min; i >0; i--) {
            if(m%i==0&&n%i==0){
                System.out.println("The maximum common divisor is:"+i);
                break;
            }
        }
        // Gets the maximum of the two numbers
        int max = Math.max(m,n);
        for (int i = max; i <=m*n ; i++) {
            if(i%m==0&&i%n==0){
                System.out.print("The minimum common multiple is:"+i);
                break;
            }
        }
    }
}

Nested loop

package Struct;

public class forDemo04 {
    public static void main(String[] args) {
        // Print 99 multiplication table
        // 1*1
        // 2*1 2*2
        // 3*1 3*2 3*3
        // 4*1 4*2 4*3 4*4
        // 5*1 5*2 5*3 5*4 5*5
        // 6*1 6*2 6*3 6*4 6*5 6*6
        // 7*1 7*2 7*3 7*4 7*5 7*6 7*7
        // 8*1 8*2 8*3 8*4 8*5 8*6 8*7 8*8
        // 9*1 9*2 9*3 9*4 9*5 9*6 9*7 9*8 9*9
        for (int i = 1; i <=9;i++) {
            for (int j = 1; j <=i; j++) {
                System.out.print(i+"*"+j+"="+i*j+"\t");
            }
            System.out.println("\n");
        }
    }
}

Nested loop

package Initial_practice;

import java.text.SimpleDateFormat;
import java.util.Date;
public class Test4 {
    public static void main(String[] args) {
        boolean flag = true;
        int balance=10000;
        String details ="";
        // Get current date
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        while(flag){
            System.out.println("---------------Jiating revenue and expenditure accounting software----------------");
            System.out.println("        1.Revenue and expenditure details");
            System.out.println("        2.Registered income");
            System.out.println("        3.Registered expenditure");
            System.out.println("        4.sign out");
            Utility utility =new Utility();
            char selection = utility.readMenuSelection();
            switch (selection){
                case '1':
                    System.out.println("---------------Current revenue and expenditure details record----------------");
                    System.out.println("Revenue and expenditure"+"\t\t"+"Account amount"+"\t\t"+"Revenue and expenditure amount"+"\t\t"+"explain"+"\t\t"+"date");
                    System.out.println(details);
                    break;
                case '2':
                    System.out.println("Current revenue amount");
                    int revenue = utility.readNumber();
                    balance+=revenue;
                    System.out.println("Description of current income");
                    String reason =utility.readString();
                    Date date = new Date();
                    details+=("income"+"\t\t"+balance+"\t\t"+"+"+revenue+"\t\t"+reason+"\t\t"+simpleDateFormat.format(date)+"\n");
                    System.out.println("---------The income registration is completed---------");
                    break;
                case '3':
                    System.out.println("Current expenditure amount");
                    int expand = utility.readNumber();
                    balance-=expand;
                    System.out.println("Description of current expenditure");
                    String info=utility.readString();
                    Date date1 = new Date();
                    details+=("income"+"\t\t"+balance+"\t\t"+"-"+expand+"\t\t"+info+"\t\t"+simpleDateFormat.format(date1)+"\n");
                    System.out.println("---------The expenditure registration is completed---------");
                    break;
                case '4':
                    System.out.println("Confirm whether to exit Y/N");
                    char c =utility .readConfirmSelection();
                    if(c=='Y'){
                        flag =false;
                    }
                    break;
            }
        }
    }
}

Tool class

package Initial_practice;

import java.util.Scanner;

public class Utility {
    Scanner scanner = new Scanner(System.in);
    //  Used to select functions
    public char readMenuSelection(){
        char c ;
        for(;;){
            String str ;
            str =new Utility().readKeyBoard(1);
            c= str.charAt(0);// Gets the first value of the string
            if(c!='1'&&c!='2'&&c!='3'&&c!='4'){
                System.out.println("Selection error, please re-enter");
            }else{
                break;
            }
        }
        return c;
    }
    // Input for income and expense amount
    // This method reads a value of no more than 4 digits from the keyboard
    public int readNumber(){
        int n;
        for(;;){
            String str = new Utility().readKeyBoard(4);
            try{
                n=Integer.parseInt(str);//Returns a string as a signed integer
                break;
            }catch (Exception exception){
                System.out.println("Digital input error, please re-enter");
            }
        }
        return n;
    }
    // Used to read revenue and expense reasons from the keyboard
    public String readString(){
        String str = new Utility().readKeyBoard(8);
        return str;
    }
    // Characters used to read exit
    public char readConfirmSelection(){
        char c ;
        for(;;){
            String str = new Utility().readKeyBoard(1).toUpperCase();// Capitalize letters
            c =str.charAt(0);
            if(c=='Y'||c=='N'){
                break;
            }else{
                System.out.println("Input error, please re-enter");
            }
        }
        return c;
    }

    public  String readKeyBoard(int limit){
        String line="";
       while(scanner.hasNext()){
           line =scanner.next();
           if(line.length()<1||line.length()>limit){
               System.out.println("Incorrect input length");
               continue;
           }else{
               break;
           }
       }
       return line;
    }
}

Array lookup

Linear search

 public void linear_search(String[] a){
        boolean flag = true;
        for (int i = 0; i <a.length ; i++) {
            if(a[i].equals("BB")){
                System.out.println("The specified character was found at:"+i);
                flag =false;
                break;
            }
        }
        if(flag){
            System.out.println("I'm sorry I didn't find it");
        }
    }

Binary search: the searched array must be in order

  public void Binary_Search(int[] b){
        int dest = 34;
        int head =0;
        int last =b.length-1;
        boolean isFlag =true;
        while(head<=last){
            int middle = (head+last)/2;
            if(b[middle]==dest){
                System.out.println("Find element at:"+middle);
                isFlag =false;
                break;
            }else if(b[middle]>dest){
                last=middle-1;
                continue;
            }else {
                head = middle+1;
                continue;
            }
        }
        if(isFlag){
            System.out.println("The element was not found");
        }
    }

object-oriented

It emphasizes the behavior of the function, taking the class or object as the minimum unit, and considering how to do it

Java classes and class members

  1. Attribute: the member variable in the corresponding class
  2. Behavior: member methods in corresponding classes

Use of classes and objects

  1. Create a class and design the members of the class
  2. Create an object of class
  3. Call the structure of an object through object. Property / object. Method
  4. If you create multiple objects of a class, each object has its own set of class properties

Use of properties in class

Attribute (member variable) vs local variable

  1. Same point

    1.1 define variable format: data type variable name = variable value

    1.2 declaration before use

    1.3 variables have their corresponding scopes

  2. difference

    2.1 attributes declared in different positions in the class: directly defined in a pair of {} of the class

    Local variable: declared in method, method parameter, code block, constructor parameter and constructor internal variable

    2.2 different permission modifiers

    Property can indicate its permission when declaring the property, and use the permission modifier

    Local variables cannot use modifiers

    2.3 default initialization value

    Property: the property of a class, which has default initialization value according to its type

    Integer (byte,short,int,long):0

    Float, double: 0.0

    Character type (char): 0/\u0000

    Boolean: false

    Reference data type (class, array, interface): null

    Local variable: no default initial value

    Be sure to display the assignment before calling

    Special: the formal parameter can be assigned when calling

    ‚Äč

Method declaration

Permission modifier return value type method name (formal parameter list){

}

  1. Permission modifier: public private protected omitted
  2. Return value type: there is a return value type and no return value. If the method has a return value type, the return value type must be specified in the method declaration. At the same time, the return keyword needs to be used in the method to return variables or constants of the specified type. If the method has no return value, void is used to represent the method declaration. If return is used in the method without return value, it means to end the method.
  3. Method name: follow the specifications and rules of identifier, "see the name and know the meaning"
  4. Parameter list: methods can declare 0 1 2 or more formats: data type 1 parameter 1 data type 2 parameter 2

practice

object array

package Initial_practice;
 /*
  Defines the Student class, which contains three attributes: Student number(int), grade state(int), grade score(int)
  Create 20 student pairs of phenomena, student numbers from grades 1 to 20 and grades are determined by random numbers
  Question 1 print out the student information of grade 3 (state value is 3)
  Question 2 use bubble sorting to sort by student grade and traverse all student information
  */
public class Test6 {
     public static void main(String[] args) {
         Student student = new Student();
         Student[] students = new Student[20];
         for (int i = 0; i < students.length ; i++) {
             // Assign values to array elements
             students[i] = new Student();
             students[i].number=(i+1);
             // Grade [0100]
             students[i].score=(int)(Math.random()*(100-0+1)+0);
             // Grade [1,6]
             students[i].state=(int)(Math.random()*(6-1+1)+1);
         }
         student.print(students);
         System.out.println("------------------------------------");
         student.searchStudent(students,3);
         System.out.println("------------------------------------");
         student.print(student.sortStudent(students));
     }

}
class Student{
    int number;// Student number
    int state;// grade
    int score;// achievement
    public void print(Student[] students){
        for (int i = 0; i < students.length-1; i++) {
            System.out.println("Student number"+students[i].number+"\t"+"grade"+students[i].state+"\t"+"achievement"+students[i].score);
        }
    }
    public void searchStudent(Student[] students,int state){
        for (int i = 0; i <students.length-1 ; i++) {
            if(students[i].state==state){
                System.out.println("Student number"+students[i].number+"\t"+"grade"+students[i].state+"\t"+"achievement"+students[i].score);
            }
        }
    }
    public Student[] sortStudent(Student[] students){
        for (int i = 0; i < students.length-1 ; i++) {
            for (int j = 0; j < students.length-i-1; j++) {
                if(students[j].score>students[j+1].score){
                    // The exchange is the array element Student object
                    Student student1 =students[j+1];
                    students[j+1] =students[j];
                    students[j] =student1;
                }
            }
        }
        return students;
    }
}

Use of anonymous objects

  1. The created object is not explicitly assigned to a variable name, that is, it is an anonymous object
  2. Anonymous objects can only be called once

Talk about methods again

Overloading of methods

In the same class, more than one method with the same name is allowed, as long as their parameter number or parameter type are different

Value Passing Mechanism of method parameters

Variable assignment: if the variable is a basic data type, the data value saved by the assigned formula variable; if the variable is a reference data type, the address value of the data saved by the variable is assigned

Method parameter value passing

  1. Formal parameter: the value of the parenthesis declared when the method is defined. Argument: the data actually passed to the formal parameter when the method is called
  2. Value Passing: if the parameter is a basic data type, the parameter is assigned to the stored value of the parameter. If the variable is a reference data type, the value assigned is the address value of the data saved by the variable

encapsulation

Hide what should be hidden, expose what should be exposed, hide the internal complexity of the object, and only disclose simple interfaces to facilitate external calls, so as to improve the scalability and maintainability of the system.

When we create a class object, we can use the object Attribute is used to assign the attribute of the object. Here, the assignment operation is restricted by the data type and storage range of the attribute, but there are no other constraints. However, in practical problems, we often need to add additional constraints to the attribute assignment, This condition cannot be reflected in the attribute declaration. We can only add restrictions through methods. We need to avoid users from adding objects again To assign a value to an attribute, you need to declare the attribute private. At this time, there is encapsulation for the attribute

Privatize the property of the class and provide a public method (get()) to get and set the value of this property

Do not expose private methods, singleton mode

The embodiment of encapsulation requires permission modifiers

jurisdictionClass interiorSame packageSubclasses of different packagesSame project
publicYYYY
protectedYYYN
defaultYYNN
privateYNNN

All four kinds of permissions can be used to modify the internal structure properties of classes and classes, and the internal classes of method constructors

For class modifiers, there are only public and default

public classes can be accessed anywhere

default can only be accessed inside the same package

constructor

construction: CCB construct or: Builder

Constructor function: create an object and initialize the properties of the object

explain

  1. create object

    Create class object: new + constructor

  2. Define the format of the constructor:

    Permission modifier class name (formal parameter list)

  3. Overloaded constructors constitute one or more classes

  4. Once the constructor is defined, the system will no longer provide the default null parameter constructor

  5. There is at least one constructor in a class

Attribute assignment process

  1. Default initial value
  2. Explicit initial value
  3. Assignment in constructor
  4. By object Object or method Attribute, assignment

The above order is 1-2-3-4

keyword

Use of this keyword

  1. this can be used to decorate: properties, methods, constructors

  2. this modifier attribute and method: understood as the current object

    2.1 in the method of class, we can use this Property or this Method calls the current property or method, but usually, we choose to omit this In special cases, if the formal parameter of the method has the same name as the attribute of the class, we must explicitly use this Variable means that the variable is an attribute, not a formal parameter.

  3. this call constructor

    3.1 in the class constructor, we can explicitly use this (formal parameter list) method to call other constructors of this class

    3.2 the constructor cannot call itself through this (formal parameter list)

    3.3 specifies that this (formal parameter list) must be declared on the first line of the current constructor

    3.4 if there are n constructors in a class, this (formal parameter list) is used in up to n-1 constructors

    3.5 inside the constructor, at most one this (formal parameter list) can be declared to call other constructors

UML class diagram

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-00StZWWj-1645145615560)(C:\Users \ ximuzi \ appdata \ roaming \ typora user images \ image-20220212174356145. PNG)]

+Indicates public type - indicates private type, # indicates protected type,

Method writing (+,) method name (parameter name: parameter type): return value type

Use of package keyword

  1. In order to better realize the management of classes in the project, the concept of package is provided
  2. Use package to declare the package to which the class or interface belongs, which is declared in the first line of the source file
  3. Package belongs to identifier and follows the naming standard of identifier. See the meaning of name
  4. Every "." Represents one file directory at a time

Interfaces and classes with the same name cannot be named under the same package. Interface classes with the same name can be named under different packages

Use of import keyword

  1. Import a class under the specified package
  2. Declaration between package and class declaration
  3. If you need to import multiple structures, you can import them side by side
  4. If the class or interface used is Java Lang package, the import structure can be omitted
  5. If the class or interface used is defined in this package, import can be omitted
  6. If a class with the same name under different packages is used in the source file, it shall be defined by using the full class name
  7. import static: imports the static definition in the specified class or interface

MVC design pattern

Trying to model layer: view display data

  1. Related tools
  2. Custom view

Controller layer: controller handles business logic

  1. Application interface related
  2. Store fragment
  3. Displays the list of adapters
  4. Service related
  5. Extracted base class

Model layer: model mainly processes data

  1. Data object encapsulation
  2. Database operation class
  3. database

Topics: Java