Circular statement in Java - array

Keywords: Java Back-end

Statements in Java

        1. Sequential structure

        2. Select structure

        if statement         switch Statements

        3. Loop structure - repeat execution

         1.for loop -- Format: for (initial condition; judgment condition; loop increment / decrement) {java code}

                  Initial condition --- determines the beginning of the cycle

                Judgment condition --- determines the end of the cycle

                Cycle increment / decrement --- control the initial condition value

                Execution process: first execute the initial condition, then execute the judgment condition. When the judgment condition result is true, execute {java code}, then download and execute the cycle increment / decrement, and then execute the judgment condition. When the judgment condition result is false, the cycle ends.

For example:

public class ForDemo{
    public static void main(String[] args) {
        for(int i=1;i<=10;i++){
            System.out.println("i=="+i);
        }     
    }
}

public class ForDemo{
    public static void main(String[] args) {
       
        for(int j=10;j>=1;j--){
            System.out.println("j=="+j);
        }
    }
}

 

public class ForDemo{
    public static void main(String[] args) {
   
        
            int num=0;
            for(int k=1;k<=10;k++){
                num=num+k;
                }
     System.out.println("num=="+num);
    }
}

          2.while loop -- format wihile (judgment condition) {java code [loop increment / decrement]}

                  Initial condition --- determines the beginning of the cycle

                Judgment condition --- determines the end of the cycle

                Cycle increment / decrement --- control the initial condition value

        Execution process: execute the judgment condition first. When the judgment condition result is true, execute the java code and continue to execute the judgment addition. When the judgment condition result is false, end the loop.

        Note 1: the initial condition is defined outside the format of while.

        Note 2: write the condition of loop increment / decrement in {java code... Last sentence}

For example:

public class WhileDemo{
    public static void main(String[] args) {
        //Output integers of 1-10
        int i=1;
        while(i<=10){
            System.out.println("i=="+i);
            i++;
        }
    }
}

public class WhileDemo{
    public static void main(String[] args) {
        //Loop out integers of 10-1
         int i=10;
         while(i>=1){
             System.out.println("i=="+i);
             i--;
         }
    }
}

public class WhileDemo{
    public static void main(String[] args) {
    //Calculate an integer of 1-10
        int i=1;
        int sum=0;
        while(i<=10){
            sum=sum+i;
            i++;
        }
        System.out.println("sum=="+sum);
    }
}

          3.do...while loop - Format: do{java code [loop increment / decrement]} while (judgment condition);

                  Initial condition --- determines the beginning of the cycle

                Judgment condition --- determines the end of the cycle

                Cycle increment / decrement --- control the initial condition value

         Execution process: first execute {java code}. When the judgment condition is executed and the result of the judgment condition is true, continue to execute {java code}, and then execute the judgment condition. When the result of the judgment condition is false, end the loop

        Note 1: the initial condition is defined outside the format of the do...while loop.

        Note 2: write the condition of increment / decrement of cycle failure in {java code... Last sentence}

For example:

public class DoWhileDemo{
    public static void main(String[] args) {
        //Loop out integers of 1-10
        int i=1;
        do{
            System.out.println("i=="+i);
            i++;
        }while(i<=10);
    }
}

public class DoWhileDemo{
    public static void main(String[] args) {
        //Loop out integers of 10-1
        int i=10;
        do{
            System.out.println("i=="+i);
            i--;
        }while(i>=1);
    }
}

public class DoWhileDemo{
    public static void main(String[] args) {
        //Calculate the integer sum of 1-10
        int i=1;
        int sum=0;
        do{
            sum=sum+i;
            i++;
        }while(i<=10);
        System.out.println("sum"+sum);
    }
}

  Compare the differences between the three cycles?

        The for loop defines the specific position of loop increment / decrement, while the while and do{}while() loops do not define the specific position of loop increment / decrement. They are often the last sentence defined in the loop body

        foe loops need to specify the number of cycles. While and do{}while() loops do not need to consider the number of cycles

For example:

import java.util.Scanner;
public class whileTest{
	public static void main(String args[]){
	Scanner input=new Scanner(System.in);
	boolean flag=true;
while(flag){
	System.out.println("Please enter the first operand");
	int num1=input.nextInt();
	System.out.println("Please enter an operation symbol");
	String   op=input.next() ;
	System.out.println("Please enter the second arithmetic number");
	int num2=input.nextInt();
switch(op){
	 case "+":System.out.println(num1+"+"+num2+"="+(num1+num2));break;
	 case "-":System.out.println(num1+"+"+num2+"="+(num1-num2));break;
	 case "*":System.out.println(num1+"+"+num2+"="+(num1*num2));break;
	 case "/":System.out.println(num1+"+"+num2+"="+(num1/num2));break;
	 case "q":System.out.println("Exit program");flag=false;break;
	default:System.out.println("Input error, unable to calculate");break;
		}	
}
}
}

  What is the difference between a while loop and a do{}while() loop?

        The while loop executes after judgment, and the do{}while() loop executes before judgment

        When the result of the initial judgment condition is false, the do{}while() loop avoids the while loop and executes the loop body once more.

For example:

public class Test2{
    public static void main(String[] args) {
//When the result of the initial judgment condition is false, the do{}while() loop will execute the loop body once more than the while loop
//do{}while() loop
        /*int i=1;
        do{
            System.out.println("i=="+i);
        }while(i<0);*/

//while Loop 
        int i=1;
        while(i<0){
            System.out.println("i=="+i);
        }
    }
}

  4. Usage and difference between break statement and continue statement

        Break statement - the execution of the table terminal loop in the loop. If the loop is nested, the loop will be interrupted at which level the break statement appears.

        Switch indicates the end of switch execution.

For example:

public class BreakDemo{
    public static void main(String args[]){
        for(int i=1;i<=10;i++){
            if(i==5){
                break;
            }
            for(int a=1;a<=10;a++){
                System.out.println("i=="+i+",a=="+a);
            }
        }
    }
}

          Continue statement -- often appears in a loop, which means to end the current loop and continue the execution of the next loop (skip this loop)

For example:

public class ContinueDemo{
    public static void main(String args[]){
        for(int i=1;i<10;i++){
            if(i==5){
                continue;
            }
            System.out.println("i=="+i);
        }
    }
}

  Arrays in Java

        1. What is an array?

        Data of the same data type -- in order -- composite data type

        2. How to define a one-dimensional array?

        Formats: data types     Array name []/ data type   [] array name;

        The definition of array is similar to that of variable, but "[]" needs to be distinguished from variable, so "[]" above is the flag of array.

        A "[]" before / after the name is a one-dimensional array, two "[] []" are binary arrays, and more than two are multidimensional arrays

        3. Create a one-dimensional array?

        The essence of creating an array is to determine the storage space of the data.

        Format:

        1. Define first and then create       Definition: data type   Array name []/ data type   [] array name;

                                          Create: array name = new array type [specified storage space];

                                            The data value of the specified storage space is tin type

        2. Define + create                 Data type array name [] = new data type [specified storage space];

                                            Data type [] array name = new data type [specified storage space];

For example:

public class ArrayDemo{
    public static void main(String args[]){
        //Define before create
        //Definition: data type array name []/ Data type [] array name;
            int intArray[];//common
            char []charArray;
        //Create: array name = new data type [specified storage space];
        //The data value of the specified storage space is of type int
            intArray=new int[4];
            charArray=new char[5];
        //Define + create  
        //Data type array name [] = new data type [specified storage space];
        int intArray2[]=new int[4];
        //Data type [] array name = new data type [specified storage space];
        char []charArray2=new char[5];
      
       
        
    }
}

        4. How to assign a value to a one-dimensional array?

                1. Assign values one by one --- that is, store data values for each storage space of the array one by one. [subscript of array required]

                    Subscript of array - because the array saves data in order, each storage space has a sequential number, and the number maintaining the array order is the subscript. You can get the data storage space of specific time through the following. Subscripts start at 0.

                The lower edge of the first storage space is 0, and so on.

                Format: array name [subscript] = data value;

                Note: an error occurs when the data stored in the array exceeds the storage space specified by the array.

                java.lang.ArrayIndexOutOfBoundsException: 

For example:

public class ArrayDemo{
    public static void main(String args[]){
         //Define before create
         //Definition: data type array name []/ Data type [] array name;
            int intArray[];//common
            char []charArray;
        //Create: array name = new data type [specified storage space];
        //The data value of the specified storage space is of type int
            intArray=new int[4];
            charArray=new char[5];
        //Define + create  
        //Data type array name [] = new data type [specified storage space];
        int intArray2[]=new int[4];
        //Data type [] array name = new data type [specified storage space];
        char []charArray2=new char[5]; 
        //Note: an error occurs when the data stored in the data exceeds the storage space specified by the array.
        //java.lang.ArrayIndexOutOfBoundsException:      
    }
}

        2. Direct assignment --- saving the data value into the array when creating the array.

                two point one     data type   Array name [] = new data type [] {data value 1, data value 2,..., data value n};

                        Storage space cannot be specified when creating an array

                two point two     Data type array name [] = {data value 1, data value 2,..., data value n};

For example:

public class ArrayDemo{
    public static void main(String args[]){
        
            int intArray[];
            intArray=new int[4];
        //Assignment: assign values one by one --- that is, store empty data values for each storage of the array one by one. [array subscript required]
        //Format: array name [subscript] = data value;
        intArray2[0]=123;
        intArray2[1]=789;
        intArray2[2]=258;
        intArray2[3]=147;
        //Direct assignment --- is to save the data value into the array when creating the array.
        //Format: data type array name [] = new data type [] {data value 1, data value 2...}
        //Storage space cannot be specified when creating an array in the form of direct assignment
        int arr1[]=new int[]{123,456,789,147};
        //Data type [] array name = {data value 1, data value 2... Data value n};
        char []chararray={'h','e','l','l','o'};

       
    }
}

        5. How to get values from an array?

                As long as we can get the storage location of the array, we can get the data values in the array

                Format: array name [subscript]

For example:

public class ArrayDemo{
    public static void main(String args[]){  
        char []chararray={'h','e','l','l','o'};
        //Array value format: array name [subscript]
        System.out.println(chararray[3]);
     
    }
}

          6. length attribute of one-dimensional array

                If the array is created by direct assignment, the length attribute indicates the number of elements.

                If the array is created by defining the creation method, the length attribute indicates that the creation of the array is the given space size, which is independent of the number of elements of the array

For example:

public class ArrayDemo{
    public static void main(String args[]){
        //If the array is created by defining the creation method, the length attribute indicates the given space size for creating the array
        //It has nothing to do with the number of elements in the array
        double douarray[]=new double[4];
        douarray[0]=55.2;
        System.out.println(douarray.length);

    }
}

          7. Loop through one-dimensional array

For example:

public class ArrayDemo{
    public static void main(String args[]){
        //Loop through one-dimensional array
        String names[]={"zhangsan","lisi","wangwu","zhaoliu"};
        //The for loop traverses the array
        /*for(int i=0;i<names.length;i++){
            System.out.println(names[i]);
        }
        */
        //while loop through array
       /* int i=0;
        while(i<names.length){
            System.out.println(names[i]);
            i++;
        }*/
        //do..while loop through the array
        /*int i=0;
        do{
            System.out.println(names[i]);
            i++;
        }while(i<names.length);*/
        //Enhanced for loop -- what's new in jdk1.5
        //For (data type variable name: array) {variable name = = each data value in the array}
        for(String name:names){
            System.out.println("Enhanced for loop--"+name);
        }
      
    }
}

          8. How to define a two-dimensional array

                Formats: data types   Array name [] [];

                          data type   [] [] array name;

For example:

public class ArrayDemo{
    public static void main(String args[]){
        //How to define a 2D data
        //Format: data type array name [] [];
        int arrtest1[][];
        //Data type [] [] array name;
        char [][]chartest;
        
    }
}

        9. How to create a two-dimensional array?

                A two-dimensional array can store data similar to a table, so we can think of a two-dimensional array as a table

                1. Define first and then create

                        data type   Array name [] [];

                        data type   [] [] array name

                        Array name = new data type [table row] [column in row];

                2. Define + create

                        data type   Array name [] [] = new data type [table row] [column in row];

                        data type   [] [] array name = new data type [table row] [column in row];

For example:

public class ArrayDemo{
    public static void main(String args[]){
        int arrtest1[][];
        char [][]chartest;
        //How to create a two-dimensional array?
        //A two-dimensional array can store data similar to a table, so we can think of a two-dimensional array as a table
        //Define before create
        //Data type array name [] [];
        //Data type [] [] array name;
        //Array name = new data type [table row] [column in row]
        arrtest1=new int[2][3];
        //Definition plus creation
        //Data type array name [] [] = new data type [table row] [column in row];
        //Data type [] [] array name = new data type [table row] [column in row]
        double douarr[][]=new double[2][3];
       
    }
}

        10. How to assign a value to a two-dimensional array?

                1. Assign values one by one --- that is, store data values for each storage space of the array one by one.

                2. Direct assignment --- saving the data value into the array when creating the array.

For example:

public class ArrayDemo{
    public static void main(String args[]){
       
        int arrtest1[][];
        char [][]chartest;
        arrtest1=new int[2][3];
        double douarr[][]=new double[2][3];
        //Two dimensional array assignment - assignment one by one - is to store data values for each storage space of the array one by one.
            douarr[0][0]=15.5;
            douarr[0][1]=20;
            douarr[0][2]=50;
            douarr[1][0]=26.2;
            douarr[1][1]=546;
            douarr[1][2]=64.2;
        //Direct assignment -- is to save the data value into the array when creating the array.
        //Format: data type array name [] [] = new data type [] [] {{data value 1, data value 2,... Data value n} {data value 1, data value 2,... Data value n}}
         //       Data type array name [] [] = {{data value 1, data value 2,..., data value n}, {data value 1, data value 2,..., data value n}
        char chharray[][]=new char[][]{{'h','e','l','l','o'},{'w','o','r','l','d'},{'h','e','l','l','o'}};

    }
}

        12. lenght attribute of two-dimensional array --- number of rows

        For example:

public class sss{
    public static void main(String args[]){
        char chharray[][]=new char[][]

{{'h','e','l','l','o'},{'w','o','r','l','d'},

{'h','e','l','l','o'}};
        //length attribute of two-dimensional array -- number of rows
        System.out.println(chharray.length);
    }
}

          13. Loop through the two-dimensional array --- use the double-layer village exchange structure, the outer control row and the inner control column

For example:

public class ArrayDemo{
    public static void main(String args[]){
        char chharray[][]=new char[][]{{'h','e','l','l','o'},{'w','o','r','l','d'},{'h','e','l','l','o'}};
        //Loop traversal of two-dimensional array -- using double-layer loop structure, outer control rows and control columns of each layer
        /*for(int i=0;i<chharray.length;i++){
            for(int j=0;j<=4;j++){
                System.out.println(chharray[i][j]);
            }
        }*/
        //Enhanced for loop
        for(char chharra[]:chharray){
            for(char value:chharra){
                System.out.println("enhance--"+value);
            }}
        
    }
}

 

          14. Know the Arrays class [array help class]

                 The Arrays class is located in the java.util package and mainly contains various methods for manipulating Arrays

                Arrays common functions (all static)

        1.void Array.sort(Object[] array) sorts arrays in ascending order

        2.void Array.sort(Object[] array,int from,int to) sorts the specified range of array elements (the sorting range is from the element subscript from to the element subscript to-1)

        3.Arrays.fill(Object[] array,Object object) can fill in the same values for array elements

        4. Arrays.fill (object [] array, int from, int to, object object object) fills in a value for some elements of the array from the start position to the end position, taking the head but not the tail

        5.Arrays.toString(Object[] array) returns the string form of the array

        

import java.util.Arrays;
public class ArrayDemo{
    public static void main(String args[]){
        //Know the Arrays class [help class for Arrays]
        //The Array class is located in the java.util package and mainly contains various methods for manipulating arrays
            char chartest1[]={'h','e','l','l','o'};
            //void Array.sort(Object[] array) sorts arrays in ascending order
                Arrays.sort(chartest1);
                for(char value:chartest1){
                    System.out.println("Arrays---"+value);
                
                }
    }
}

15. Memory structure of array

Posted by HA7E on Fri, 29 Oct 2021 05:48:30 -0700