Java foundation -- process control, method and array---

Process control

User interaction, Sanner

  • Function: get user input through Scanner class

  • Basic syntax:

  • Obtain the string through the next () and nextline() methods of the Scanner class;

  • Before reading, you can use hasNext() and hasNextLine() to determine whether there is still input data (which can be used for loop condition judgment)

    Scanner s = new Scanner(System.in);
    //Enter hello world
    String str = s.next();
    System.out.println("str by "+str);   //Can't get a string with spaces, get hello
    String str1 = s.nextLine();
    System.out.println("str1 by "+str1);  //Take carriage return as the ending character to get hello world
    s.close();   //All classes of I/O flow shall be closed when they are used up
    
    
    while(s.hasNextDouble()){
                double x = s.nextDouble();
                account++;
                sum = sum + x;
            }
     System.out.println("share"+account+"Number, total"+sum);
     s.close();
     System.out.println("Current input No"+account+"number");
    

Sequential structure

Select structure

  • if radio

  • if double selection

  • if multiple selection

  • Nested if

  • switch multiple choices (equivalent judgment, can match string)

    Pay attention to add break after each case is written, otherwise it will penetrate

Cyclic structure

  • while Loop
  • do...while Loop
  • For loop -- enhanced for

break & contine

  • break can be used in the body of any loop statement to forcibly exit the loop (also used in switch statements)
  • continue is used to terminate a loop process, skip the unexecuted statements in the loop body, and then judge the next loop

practice

Print triangle isosceles triangle diamond

method

Method definition and call

  • Method: a collection of statements that perform a function (it's best to keep atomicity, and a method implements a function)

  • Naming: initial lowercase, hump naming

  • Composition: modifier (public) return value type method name parameter type method body

  • Call: object name Method name (argument list)

    ~ when a method returns a value, the method call is usually regarded as a value int larger = max(30,40);

    ~ if the return value of the method is void, the method call must be a statement system out. println("Hello,world");

Method overloading

  • What? Overloading is in a class with the same function name and different formal parameters
  • Method overloading means that the method name is the same and the parameter list is different (the number is different or the type is different or the parameter arrangement order is different)

Variable parameter (indefinite item)

  • In the method declaration, add an ellipsis after specifying the parameter type (you can pass several) (int...i)
  • A method can only specify one variable parameter and must be the last parameter of the method

Recursion -- stack mechanism

  • What--- A method calls itself
  • Structure: recursive head (when not called, run out of the cage) recursive body (when called)

array

Declaration creation

  • Declaration - dataType[] name; (preferred) or datatype name []; (used in c and c + +)
  • Create - use new operator: dataType[] name = new dataType[size]
  • Array elements are accessed by index, and the array index starts from 0
  • Initialization: static, dynamic
  • Array is a reference type. Array can also be regarded as an object. Array elements are the member variables of the object; Once the array is allocated space, it is implicitly initialized (the default value is 0)
  • Once created, the size cannot be changed.
  • Java Memory Analysis

Heap -- stores new objects and arrays, and does not store other object references

Stack -- store basic variable types (numeric, character, Boolean; including specific values), variables of reference objects (store the specific address of the reference in the heap) (string is not the basic data type!!!)

Note: in Java = = compares the values in the stack, and equals() compares the values in the heap

Method area -- shared by all threads, including all class and static variables

use

  • for loop -- print array elements

  • For each, enhance the input and output of the for loop

  • Array as method input parameter (amount...)

  • Array as return value -- invert array

Multidimensional array

  • Two dimensional array: array of arrays, nested array: int a[][] [][] =new int [2] 5

     //Traversal output
     for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                 System.out.print(array[i][j]+" ");
                }
                System.out.println();
      }
    
    

Arrays class

  • For a tool class of array, you can call it directly with the class name -- Arrays Method (see jdk help document for details)
int[] a = {1,2,3,4,236,650,895,0,7,5};
//Print array elements
System.out.println(a);  //Print directly, (hashcode) results:[ I@76ed5528
System.out.println(Arrays.toString(a)); //Arrays class method, output array elements, very convenient!!!
 Arrays.sort(a);  //Sort array a in ascending order by default
 Arrays.fill(a,2,4,0); //The array is filled with 0 between 2 and 4
  • Bubble sorting: it can be optimized by adding a flag to reduce meaningless comparison

    public static int[] sort(int[] array){
            int temp = 0;
            boolean flag = false; //By reducing the meaningless comparison of flag identification bits, it can be optimized
            //Outer circle, judge how many times to go
            for (int i = 0; i < array.length-1; i++) {
                 //The inner loop judges what to do each time. If the latter one is smaller than the previous one, exchange positions
                 for (int j = 0; j < array.length-1-i; j++) {
                     if(array[j+1] < array[j]){
                         temp = array[j+1];
                         array[j+1] = array[j];
                         array[j] = temp;
                         flag = true;
                          }
                    if(!flag){
                        break;
                    }
                     
                 }
                 }
            return array;
        }
    

Sparse array

  • Most elements in an array are 0 or the same value, which can be saved by sparse array

  • Treatment method:

    1) Record the number of different values (excluding 0) in rows and columns;

    2) Recording the rows, columns and values of different value elements in an array can reduce the size of the program;

  • Code: the sparse array is fixed to 3 columns: row, column and value; If there are sum different values, then there are sum+1 rows (the first row holds a total of several rows, columns and values)

    //Convert to sparse array
           //Number of valid values obtained by traversal
            int sum = 0;
            for (int i = 0; i < 11; i++) {
                for (int j = 0; j < 11; j++) {
                    if (array[i][j] != 0) {
                        sum++;
                    }
                }
            }
            System.out.println("The number of valid values is" + sum);
            //Create a sparse array
            int[][] array2 = new int[sum + 1][3];
            //Assignment -- assign a value to the first row (the initial array has several rows, columns, and several valid values)
            array2[0][0] = 11;
            array2[0][1] = 11;
            array2[0][2] = sum;
            //Traverse the two-dimensional array and store non-zero values in the sparse array
            int count = 0;
            for (int i = 0; i < array.length; i++) {
                for (int j = 0; j < array[i].length; j++) {
                    if (array[i][j] != 0) {
                        count++;    //If the number is not 0, it is on the first row of the coefficient matrix
                        array2[count][0] = i;   //The number of rows stored in the original array in column 0 of this row
                        array2[count][1] = j;   //The number of columns stored in the original array in the first column of this row
                        array2[count][2] = array[i][j]; //The value stored in the original array in column 2 of this row
                    }
                }
    
            }
            //Output sparse array
            for (int i = 0; i < sum + 1; i++) {
    //            System.out.println(array2[i][0] + "\t" + array2[i][1] + "\t" + array2[i][2] + "\t");
                for (int j = 0; j <3 ; j++) {
                    System.out.print(array2[i][j]+"\t");
    
                }
                System.out.println();
            }
    

Keywords: Java

Added by bgbs on Sun, 09 Jan 2022 11:01:48 +0200