Java basics day 4
[learning objectives] understanding, understanding, application and memory
1. [application] installation and use of IDEA tools
a) [application] master the installation of idea development tools
b) [application] be able to create Java projects using idea
c) [application] be able to create packages and classes using idea
d) [understanding] Java project directory of idea
e) [understanding] idea font setting
f) [application] common development shortcut keys of idea
g) [understand] import and delete items
2. [understanding] one dimensional array memory structure and static initialization
a) [memory] it can explain which areas of memory in Java are divided
b) [understanding] be able to explain the distribution diagram of an array in memory according to the code
c) [understanding] be able to explain the distribution diagram of two arrays in memory according to the code
d) [understanding] it can explain the memory diagram of two arrays pointing to the same address value according to the code
e) [application] can independently write out the static initialization of array initialization
3. [application] common problems and exercises of one-dimensional array
a) [application] be able to write the code of two common small problems of array operation independently
b) [application] be able to independently write the code of traversing array for array operation
c) [application] be able to independently write the code for obtaining the maximum value of array operation
4. [understanding] definition and use of two-dimensional array
a) [understanding] be able to explain the overview and basic use of two-dimensional array
b) [application] be able to write two-dimensional array traversal code independently
5. [application] tool class of Arrays
a) [application] API usage of Arrays
b) [understanding] analysis of quick sort principle
c) [application] bubble sorting implementation
d) [understanding] half search method
e) [application] array copy and capacity expansion
Chapter 1 use of development tool IntelliJ IDEA
1.1 overview of development tools
IDEA is an integrated development tool (IDE) for Java, which is written in Java language. Therefore, you need to have a JRE running environment and configure environment variables. It can greatly improve our development efficiency. It can compile automatically and check for errors. In the company, IDEA is used for development.
1.2 IDEA software installation
This software integrates 32-bit and 64 bit. Double click ideaiu-2019.2 4. Exe enter the installation.
**PS: * * see installation and use of IDEA development tools. pdf for details
1.3 common shortcut keys of idea
Alt+Enter import package, automatically fix code
Ctrl+Y delete the line where the cursor is located
Ctrl+D copy the contents of the line where the cursor is located and insert it below the cursor position
Ctrl+Alt+L format code
Ctrl + / single line comment
Ctrl+Shift + / select code comment, multiline comment, and then press cancel comment
Alt+Ins automatically generates code, toString, get, set and other methods
Alt+Shift + up and down arrows move the current line of code
1.4 font setting
The default font of the IDEA tool is very small, and the output font of the code editor and console need to be adjusted.
Click file - > Settings - > editor - > font on the menu bar to modify the font.
1.5 project directory of idea
The project we created is under the demo of the project directory
. IDEA directory and demo IML has nothing to do with development. It is used by the IDEA tool itself
The out directory stores the compiled class file
The src directory is where we write the java source file
1.6 shortcut keys for idea modification
In the IDEA tool, the shortcut of Ctrl + space can help us complete the code, but this shortcut conflicts with the shortcut of input method switching in Windows. You need to modify the shortcut in the IDEA.
1. File->Settings->keymap->Main menu->code->Completion->Basic
2. Double click basic - > remove - > Ctrl + space
3. Double click basic - > Add keyboard - > type Alt + / - > click OK
1.7 IDEA importing and closing projects
1. Close the existing project in IDEA
File->Close Project
After file - > close project, the IDEA returns to the just started interface. Click X on the project, and there will be no project in the IDEA
2. On the IDEA startup interface, click OPEN and select the project directory to OPEN it
3. If you want to OPEN multiple projects at the same time through IDEA, click OPEN to OPEN the project and click the New Window button
Chapter 2 array
/** * The concept of array: a set of containers with the same data type and fixed length * * Array features: * 1.The array itself is a reference data type * 2.Basic data types and reference data types are allowed to be stored in the array * 3.Once the length is defined, it cannot be modified * 4.Storing elements of the same data type * * * One dimensional array * 1.How to declare? * 1.1 int[] arr = new int[3]; * 1.2 String[] strs = {"aaa","bbb","ccc","ddd"}; * 2.How to assign values? * 2.1 Directly assign int[] arr = {10,20,30} when declaring; * 2.2 Assignment by subscript syntax: array name [subscript] = value; * 3.How to get the value? * 3.1 Take the value of for (variable initialization; variable < array. length; variable + +) {/ / array name [subscript]} * 3.2 The iterator value for (element type in the array, temporary variable name: array name) {/ / temporary variable name} is used more in the later stage */ public class OneArrayDemo1 { public static void main(String[] args) { /* Declaration method 1: specify the length of the array 1.arr1 The elements in the array are all int data types, basic data types 2.arr1 Three elements can be stored in the array 3.arr1 The default value of all elements in the array is 0 4.arr1 Object, one-dimensional array type of int, reference data type */ int[] arr1 = new int[3]; //Subscript range: 0~len-1 //Assignment by subscript arr1[0] = 52; arr1[1] = 46; //Take value by subscript South generate printout directly ctrl+d copy the previous line System.out.println(arr1[0]); //52 System.out.println(arr1[1]); //46 System.out.println(arr1[2]); //0 //System.out.println(arr1[3]); // Array index out of bounds exception ArrayIndexOutOfBoundsException: 3 System.out.println("-----------fori---------------"); /* Declaration method 2: specify the elements in the array 1.strs The elements in the array are of String type and reference data type 2.strs Four elements are stored in the array 3.strs Object, one-dimensional array type of String, reference data type */ String[] strs = {"aaa","bbb","ccc","ddd"}; //Iterative method 1: operate the array name through subscript Iteration of quick array generation for for (int i = 0; i < strs.length; i++) { //i array name [subscript] System.out.println(strs[i]); } System.out.println("-----------foreach---------------"); //Iterative method 2: strengthen the foreach array name of the for loop Iteration of for quick array generation for (String str : strs) { //For (element type temporary variable name in array: array name) {/ / temporary variable name, that is, each element in the array} System.out.println(str); } } }
2.1 array overview
**Container: * * stores multiple data together, and each data is called the element of the container.
So what is an array? What are the characteristics?
An array is something (container) that stores multiple variables (elements)
The data types of these variables should be consistent
Array concept: an array is a container for storing data with a fixed length to ensure that the data types of multiple data are consistent.
Array features:
1. Fixed array length
2. The data types of the elements stored in the array container are consistent
2.2 definition format of array
2.2. 1 array concept
An array is a container that stores multiple elements of the same data type.
Arrays can store both basic data types and reference data types.
2.2. 2 definition format of array
Format 1: data type [] array name; int[] arr;
Format 2: data type array name [];
Note: after these two definitions are completed, there is no element value in the array.
2.3 initialization of array
2.3. 1 overview of array initialization
Arrays in Java must be initialized before they can be used.
The so-called initialization is to allocate memory space for the array elements in the array and assign values to each array element.
2.3. 2 initialization method of array
2.3. 2.1 dynamic initialization: only the array length is specified during initialization, and the system allocates the initial value for the array
Formats: data types[] Array name = new data type[Array length];
Array length is actually the number of elements in the array.
2.3. 2.2 case 1
//Array: a container that stores multiple elements of the same data type. //Dynamic initialization: data type [] array name = new data type [array length]; public class ArrayDemo1 { public static void main(String[] args) { //Data type [] array name = new data type [array length]; The default value of elements in the array is 0 int[] arr = new int[3]; /* * Left: * int:Indicates that the data type of the elements in the array is int * []:This is an array * arr:Is the name of the array * right: * new:Allocate memory space for arrays * int:Indicates that the data type of the elements in the array is int * []:This is an array * 3:The length of an array is actually the number of elements in the array */ } }
2.3. 2.3 static initialization: specify the initial value of each array element during initialization, and the array length is determined by the number of elements
Formats: data types[] Array name = new data type[]{Element 1,Element 2,Element 3...}; Formats: data types[] Array name = {Element 1,Element 2,Element 3...};
2.3. 2.4 case 2
//Format of static initialization //Data type [] array name = new data type [] {element 1, element 2,...}; //Simplified format: data type [] array name = {element 1, element 2,...}; public class ArrayDemo2 { public static void main(String[] args) { //Define array int[] arr1 = new int[]{1,2,3}; int[] arr2 = {1,2,3}; } }
2.4 memory allocation of array
**Memory overview: * * memory is an important original and temporary storage area in the computer. It is used to run programs. The program we write is stored in the hard disk. The program in the hard disk will not run. It must be put into the memory to run. After running, the memory will be emptied.
2.4.1 JVM memory partition
Java programs need to allocate space in memory when running. In order to improve the operation efficiency, the space is divided into different regions, because each region has a specific data processing mode and memory management mode.
The stack stores local variables. - A local variable is a variable defined inside a method - Recycle immediately after use. Heap storage new Out of something, the real object. - Each object has a first address - The data of each object has a default value - After use, it will be collected by the garbage collector when it is idle
2.4. 2 memory diagram of an array
Requirements: define an array and output the array name and elements. Then assign values to the elements in the array and output the array name and elements again.
2.4. 2.1 case III
/** * Requirements: define an array and output the array name and elements. Then assign values to the elements in the array and output the array name and elements again. */ public class ArrayTest1 { public static void main(String[] args) { //Define an array int[] arr = new int[3]; //Output array name and elements System.out.println(arr); System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); //Assign values to elements in the array arr[0] = 100; arr[2] = 200; //Output the array name and elements again System.out.println(arr); System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); } }
2.4. 2.2 code memory diagram
2.4. 3 memory diagram of two arrays
Requirements: define two arrays and output array names and elements respectively. Then assign values to the elements in the array, and output the array name and elements again
2.4. 3.1 case 4
/** * Requirements: define two arrays and output array names and elements respectively. Then assign values to the elements in the array, and output the array name and elements again. */ public class ArrayTest2 { public static void main(String[] args) { //Define two arrays int[] arr = new int[2]; int[] arr2 = new int[3]; //Output the array name and elements respectively System.out.println(arr); System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr2); System.out.println(arr2[0]); System.out.println(arr2[1]); System.out.println(arr2[2]); //Then assign values to the elements in the array respectively arr[1] = 100; arr2[0] = 200; arr2[2] = 300; //Output the array name and elements again System.out.println(arr); System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr2); System.out.println(arr2[0]); System.out.println(arr2[1]); System.out.println(arr2[2]); } }
2.4. 3.2 code memory diagram
2.4. 4 two arrays point to the memory map of the same address
Requirements: define two arrays. First define an array, assign values, and output. Then, when defining the second array, assign the address of the first array to the second array. Then assign a value to the second array and output the names and elements of the two arrays again
//Two arrays point to the same block address public class OneArrayDemo2 { public static void main(String[] args) { int[] arr = new int[3]; //The assignment between arrays is given an address, that is, the two arrays point to the same block of address int[] brr = arr; brr[0] = 10; System.out.println("arr[0] = "+arr[0]); System.out.println("brr[0] = "+brr[0]); } }
2.4. 4.1 case 5
/** * Requirements: define two arrays. First define an array, assign values, and output. Then, when defining the second array, assign the address of the first array to the second number * Group. Then assign a value to the second array and output the names and elements of the two arrays again. */ public class ArrayTest3 { public static void main(String[] args) { // First define an array, assign value and output int[] arr = new int[3]; arr[0] = 100; arr[1] = 200; arr[2] = 300; System.out.println(arr); System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); // Then, when defining the second array, assign the address of the first array to the second array int[] arr2 = arr; // Then assign a value to the second array arr2[0] = 111; arr2[1] = 222; arr2[2] = 333; // Output the names and elements of the two arrays again System.out.println(arr); System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); System.out.println(arr2); System.out.println(arr2[0]); System.out.println(arr2[1]); System.out.println(arr2[2]); } }
2.4. 4.2 code memory diagram
2.5 use of arrays
2.5. 1 element access of array
Index: each element stored in the array will automatically have a number, starting from 0. This automatic number is called the array index, which can access the elements in the array through the index of the array.
Format: array name [index]
Array length attribute: each array has a length and is fixed. Java gives an attribute to the array to obtain the length of the array. The statement is: array name Length, the execution result of the attribute length is the length of the array, and the result of type int.
The maximum index value of the array is: array name length-1 .
Index access to elements in the array:
Array name [index] = numeric value, assigning values to the elements in the array
Variable = array name [index], get the elements in the array
2.5. 2 case 6
public class ArrayDemo3 { public static void main(String[] args) { //Data type [] array name = new data type [array length]; int[] arr = new int[3]; //[ I@3fa5ac , address value System.out.println(arr); //It's meaningless for us to get the address value. What I want is the data value in the array. What should I do? //Don't worry, java has already figured it out for you //In fact, each element in the array is numbered. The number starts from 0. The maximum number is the length of the array - 1 //With the combination of array name and number, we can obtain the elements with the specified number in the array. The professional name of this number is index //Format: array name [number] < -- > array name [index] System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); } }
2.5. 3 two small problems in the use of arrays
ArrayIndexOutOfBoundsException array out of bounds exception
Null pointerexception null pointer exception
2.5. 4 case 7
/** * Array out of bounds exception, null pointer exception * * Two common questions: * A:java.lang.ArrayIndexOutOfBoundsException * Array out of bounds exception * The reason is that you access non-existent index elements. * B:java.lang.NullPointerException * Null pointer exception * Cause: the array does not point to the data in the heap memory. You also use the array name to access the elements. * * Why should we remember such a small problem? * Programming is not only to write the code, but also to solve the problem quickly when there is a problem. */ public class ArrayDemo4 { public static void main(String[] args) { // Define array int[] arr = {1, 2, 3}; //ArrayIndexOutOfBoundsException array out of bounds exception //System.out.println(arr[3]); //Reference type: class, interface, array //Constant: null, which can be assigned to a reference type //arr = null; System.out.println(arr[1]); } }
2.5. 5 iteration of array
Requirements: declare the array, iterate (output each element in the array in turn), and obtain the number of elements in the array: array name length
2.5. 6 case 8
public class ArrayDemo5 { public static void main(String[] args){ //Declare array, create array int[] arry = new int[]{1,2,3,4,5}; //Value /* System.out.println(i[0]); System.out.println(i[1]); System.out.println(i[2]); System.out.println(i[3]); System.out.println(i[4]); */ //The first type: for loop, iterative value for(int j = 0;j < arry.length;j++){ System.out.println(arry[j]); } //The second is for loop, which strengthens for for(int x : arry){ System.out.println(x); } } }
2.6 classroom practice of one-dimensional array
//Exercise 1: Requirements: define an integer array, enter 5 elements from the keyboard, and find the maximum value //Exercise 2: there is a sequence: 8,4,2,1,23344,12. At this time, input any data from the keyboard to judge whether the sequence contains this number //Method 1 //Method 2: first bubble sort, and then half check to find out whether it contains //Exercise 3: exchange an array element in reverse order, int[] a ={5,11,15,24,36,47,59,66}; After exchanging elements, int[] a = {66,59,47,36,24,15,11,5}
//Exercise 1: Requirements: define an integer array, enter 5 elements from the keyboard, and find the maximum value public class OneArrayTest1 { public static void main(String[] args) { //1. Define integer array int[] arr = new int[5]; //The default value is 0 //2. Enter 5 elements from the keyboard Scanner scanner = new Scanner(System.in); System.out.println("Please enter five elements:"); for (int i = 0; i < arr.length; i++) { //i subscript arr[i] = scanner.nextInt(); //Array assignment: array name [subscript] = value } //output for(int a:arr){ System.out.print(a+"\t"); } //3. Find the maximum value int max = arr[0]; //Takes the first element in the array as the maximum value for(int i=1;i<arr.length;i++){ //i subscript if(max<arr[i]){ max = arr[i]; } } System.out.println("Maximum max = "+max); } } //Exercise 2: there is a sequence: 8,4,2,1,23344,12. At this time, input any data from the keyboard to judge whether the sequence contains this number (the first method) public class OneArrayTest2 { public static void main(String[] args) { //1. Define a one bit array int[] arr = {8,4,2,1,23,344,12}; //2. Input any data from the keyboard Scanner sc = new Scanner(System.in); System.out.println("Please enter a data:"); int m = sc.nextInt(); //3. Judge whether this number is included in the sequence boolean flag = true; //identifier for(int a:arr){ if(m == a){ System.out.println("contain"); flag = false; break; } } if(flag){ System.out.println("Not included"); } } } //Exercise 2: there is a sequence: 8,4,2,1,23344,12. At this time, input any data from the keyboard to judge whether the sequence contains this number (the second method) public class BinaryDemo { public static void main(String[] args) { //1. Define an array int[] arr = {8,4,2,1,23,344,12}; //2. Sort the array Arrays.sort(arr);//Quick sort using the Arrays tool class System.out.println("After sorting:"+Arrays.toString(arr)); //Use the toString printout of the Arrays tool class //3. Half search method query int left = 0; int right = arr.length-1; int middle = 0; Scanner scanner = new Scanner(System.in); System.out.println("Please enter query data:"); int key = scanner.nextInt(); boolean flag = true; while(left<=right){ //Calculate the value of the middle position middle = (left+right)/2; if(key > arr[middle]){ //Consider the right side of the middle left = middle + 1; }else if(key < arr[middle]){ //Consider the left side of the middle right = middle - 1; }else if(arr[middle] == key){ System.out.println("contain"); flag = false; break; } } if(flag){ System.out.println("Not included"); } } } //Exercise 3: exchange an array element in reverse order, int[] arr ={5,11,15,24,36,47,59,66}; //After exchanging elements, int[] arr = {66,59,47,36,24,15,11,5} public class OneArrayTest3 { public static void main(String[] args) { int[] arr = {5,11,15,24,36,47,32,59,66}; for(int i=0;i<arr.length/2;i++){ //i 0~3 //arr[i] value of the leading bit arr[arr.length-1-i] value of the trailing bit int temp = arr[i]; arr[i] = arr[arr.length-1-i]; arr[arr.length-1-i] = temp; } for (int a : arr) { System.out.print(a+"\t"); } } }
2.7 two dimensional array
/** * The concept of two-dimensional array: container. The elements in two-dimensional array are one-dimensional arrays * * 1.Declaration of two-dimensional array * 1.1 Specify length directly * int[][] arr1 = new int[2][]; * int[][] arr2 = new int[2][3]; * 1.2 Specify elements directly * int[] a = {1,2,3}; * int[] b = {10,20,30}; * int[][] arr3 = {a,b}; * int[][] arr4 = { {1,2,3} , {10,20,30} }; * * 2.Assignment of two-dimensional array * * 3.Value of two-dimensional array */ public class TwoArrayDemo { public static void main(String[] args) { //Method 1: specify the length int[][] arr1 = new int[2][]; int[][] arr2 = new int[2][3]; //First dimension assignment arr1[0] = new int[2]; arr1[1] = new int[3]; //Assignment of the second dimension arr1[0][1] = 15; arr1[1][0] = 25; //Value for(int i=0;i<arr1.length;i++){ //Length of the first dimension of line i for(int j=0;j<arr1[i].length;j++){ //Length of the second dimension of column j System.out.print(arr1[i][j]+"\t"); } System.out.println(); } System.out.println("==========================="); //Method 2: specify elements int[] a = {1,2,3}; int[] b = {10,20,30}; int[][] arr3 = {a,b}; int[][] arr4 = {{1,2,3},{10,20,30,40},{11,22}}; for(int i=0;i<arr4.length;i++){ //i line arr4 length for(int j=0;j<arr4[i].length;j++){ //Column j arr4 [i] length System.out.print(arr4[i][j]+"\t"); } System.out.println(); } } }
2.7. 1 overview of 2D arrays
Our geek camp programmers' java basic classes have many students in each class, so we can store them in arrays, and we have many java basic classes at the same time. This should also be stored in an array. How to represent such data? Java provides a two-dimensional array for us to use.
This shows that a two-dimensional array is actually an array whose elements are one-dimensional arrays.
2.7. 2 two dimensional array format
Define format: data type[][] Array name; Data type array name[][]; Not recommended data type[] Array name[]; Not recommended
Initialization method: //Dynamic initialization: //m indicates how many one-dimensional arrays this two-dimensional array has //n represents the number of elements in each one-dimensional array data type[][] Variable name = new data type[m][n]; //Static initialization: data type[][] Variable name = new data type[][]{{Element},{Element},{Element}}; //Simplified format: data type[][] Variable name = {{Element},{Element},{Element}};
2.7. 2.1 case 9
public class TwoArrayDemo1 { public static void main(String[] args) { // Data type [] [] array name = {{element...}, {element...}, {elements...},...}; int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; System.out.println(arr); // [[I@104c575 System.out.println(arr.length); // The number of one-dimensional arrays in a two-dimensional array System.out.println(arr[0]);// [I@3fa5ac System.out.println(arr[0].length); System.out.println(arr[1]);// [I@95cfbe System.out.println(arr[2]);// [I@179dce4 //How do I get the elements of a two-dimensional array? System.out.println(arr[0][0]); System.out.println(arr[1][1]); System.out.println(arr[2][0]); } }
2.7. 3 traversal of two-dimensional array
Traversal idea: first, use the loop to traverse each one-dimensional array stored in the two-dimensional array, and then use the loop to traverse the elements in the one-dimensional array for each one-dimensional array
2.7. 3.1 case 10
public class TwoArrayDemo2 { public static void main(String[] args) { //Define a 2D array int[][] arr={{1,2,3},{4,5,6},{7,8,9}}; //One dimensional array name in two-dimensional array: two-dimensional array name [index] //arr[0] In fact, it is the name of the first one-dimensional array in the two-dimensional array //arr[1] In fact, it is the name of the second one-dimensional array in the two-dimensional array //arr[2] In fact, it is the name of the third one-dimensional array in the two-dimensional array /* //Elements of the first one-dimensional array for(int x=0;x<arr[0].length;x++){ System.out.println(arr[0][x]); } //Elements of the second one-dimensional array for(int x=0;x<arr[1].length;x++){ System.out.println(arr[1][x]); } //Elements of the third one-dimensional array for(int x=0;x<arr[2].length;x++){ System.out.println(arr[2][x]); }*/ //Improved code, length of two-dimensional array for(int y=0;y<arr.length;y++){ for(int x=0;x<arr[y].length;x++){ System.out.println(arr[y][x]); } } System.out.println("---------------"); //Final improvement for(int y=0;y<arr.length;y++){ for(int x=0;x<arr[y].length;x++){ System.out.print(arr[y][x]+" "); } System.out.println(); } } }
2.8 classroom practice of two-dimensional array
//Exercise 1: save a Tang poem (five or seven characters) with a two-dimensional character array. Each line represents a sentence. It is required to output the Tang poem in the way of ancient Chinese (arranged in vertical lines from right to left)... public class TwoArrayTest1 { public static void main(String[] args) { char[][] cs = { {'Bed','front','bright','month','light',','}, {'Doubt','yes','land','upper','frost','. '}, {'lift','head','at','bright','month',','}, {'low','head','thinking','so','country','. '} }; for(int i=0;i<cs.length;i++){ //4 rows and 6 columns for(int j=0;j<cs[i].length;j++){ System.out.print(cs[i][j]+"\t"); } System.out.println(); } System.out.println("---------------------------"); for(int i=0;i<cs[0].length;i++){ //I 0 ~ 5 6 lines for(int j=0;j<cs.length;j++){ //J 0 ~ 3 4 columns System.out.print(cs[3-j][i]+"\t"); } System.out.println(); } System.out.println("------------The second way---------------"); for(int i=0;i<cs[0].length;i++){ //I 0 ~ 5 6 lines for(int j=cs.length-1;j>=0;j--){ //J 0~3 4 columns / / output in reverse order System.out.print(cs[j][i]+"\t"); } System.out.println(); } } } //Exercise 2: Jiugong grid 3 08 01 06 03 05 07 04 09 02 5 17 24 01 08 15 23 05 07 14 16 04 06 13 20 22 10 12 19 21 03 11 18 25 02 09 import java.util.Scanner; //squared paper for practicing calligraphy public class TwoArrayTest2 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Please enter the number of Jiugong squares (it must be)>1 Odd number of:"); int N = scanner.nextInt(); while (N<=1 || N%2==0){ System.out.println("Please enter the number of Jiugong squares (it must be)>1 Odd number of:"); N = scanner.nextInt(); } //1. Create a two-dimensional array of N*N int[][] arr = new int[N][N]; //2. The position of the first value is in the middle of the first row int x = 0; int y = N/2; //3. Circular judgment assignment for(int value=1;value<=N*N;value++){ //assignment arr[x][y] = value; //Upper right corner x--; y++; if(x<0 && y<N){ //Row out of bounds, column out of bounds x = N-1; //The last row of the current column }else if(x>=0 && y>=N){ //Column out of bounds, row out of bounds y = 0; //The first column of the current row }else if((x<0&&y>=N) || arr[x][y]!=0){ //The rows and columns are out of bounds. There is a value in the upper right corner x+=2; y--; //Directly below the original value } } //4. Output for (int i=0;i<arr.length;i++){ for (int j=0;j<arr[i].length;j++){ System.out.print((arr[i][j]<10?"0"+arr[i][j]:arr[i][j])+"\t"); } System.out.println(); } } } //Exercise 3: find the sum of diagonal elements of a two-dimensional array 3X3 public class TwoArrayTest3 { public static void main(String[] args) { //Declaration array int[][] arr = new int[3][]; //assignment arr[0] = new int[]{1,2,3}; arr[1] = new int[]{4,5,6}; arr[2] = new int[]{7,8,9}; //Find the sum of diagonal elements int sum1 = 0; int sum2 = 0; for(int i=0;i<arr.length;i++){ for(int j=0;j<arr[i].length;j++){ //Positive diagonal if(i==j){ sum1+=arr[i][j]; } //Sub diagonal if(i+j==2){ sum2+=arr[i][j]; } } } System.out.println("sum1 = "+sum1); System.out.println("sum2 = "+sum2); } }
Chapter 3 Arrays class
3.1 tool class of arrays
3.2 analysis of quick sort principle
3.3 realize bubble sorting
Requirements: input ten integers from the keyboard and output them in ascending order; (bubble sort)
/** * Bubble sorting */ public class BubbleDemo { public static void main(String[] args) { int[] arr = {8,4,2,1,23,344,12}; //i number of comparison rounds for (int i = 0; i < arr.length-1; i++) { //j times for (int j = 0; j < arr.length-i-1 ; j++) { //compare if(arr[j]>arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } //output for (int a : arr) { System.out.println(a); } } }
3.4 half search method
Requirement: there is a number sequence: 8,4,2,1,23344,12. At this time, enter any data from the keyboard to judge whether the number is included in the number sequence
/** * Binary search (half search): Based on ordered arrays * Exercise 2: there is a sequence: 1,2,4,8,12,23344. At this time, input any data from the keyboard to judge whether the sequence contains this number */ public class BinaryDemo { public static void main(String[] args) { int[] arr = {1,2,4,8,12,23,344}; // subscript int left = 0; int right = arr.length - 1; int middle = 0; //key Scanner scanner = new Scanner(System.in); System.out.println("Enter keywords:"); int key = scanner.nextInt(); boolean flag = true; //As long as this condition is met, you can always compare circularly while(left <= right){ //Calculate middle middle = (left+right)/2; //Compare compares key with arr[middle] if(arr[middle] > key){ right = middle - 1; }else if(arr[middle] < key){ left = middle + 1; }else if(arr[middle] == key){ flag = false; System.out.println("contain"); break; } } if(flag){ System.out.println("Not included"); } } }
3.5 array copy and capacity expansion
/** * Arrays Array tool class copy */ public class ArraysDemo1 { public static void main(String[] args) { /** * System * src Source array srcPos source array start position dest destination array destPos destination array start position lengthcopy length * static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) */ int[] arr = {10,25,3,45,12}; int[] brr = new int[arr.length]; System.arraycopy(arr,0,brr,0,arr.length); System.out.println("arr:"+Arrays.toString(arr)); System.out.println("brr:"+Arrays.toString(brr)); //equals compares the contents of elements in two arrays System.out.println(Arrays.equals(arr,brr)); //true //==Compare addresses System.out.println(arr == brr); //false /** * Arrays * original Source array newLength the length of the new array * static int[] copyOf(int[] original, int newLength) */ int[] crr = Arrays.copyOf(arr, arr.length); System.out.println("crr:"+Arrays.toString(crr)); System.out.println("equals:"+Arrays.equals(arr,crr)); //true System.out.println("==:"+(arr==crr)); //false //Array expansion int[] drr = Arrays.copyOf(arr, arr.length*3/2+1); int[] err = Arrays.copyOf(drr, drr.length*3/2+1); System.out.println("drr:"+Arrays.toString(drr)); System.out.println("err:"+Arrays.toString(err)); } }
3.6 other methods in API
/** * Arrays Tool sort dichotomy */ public class ArraysDemo2 { public static void main(String[] args) { int[] arr = {10,25,9,12,11,7}; /** * Sort first * static void sort(int[] a) * First parameter: array involved in sorting, second parameter: start position, third parameter: end position (not available) * static void sort(int[] a, int fromIndex, int toIndex) */ Arrays.sort(arr); //Arrays.sort(arr,1,4); System.out.println(Arrays.toString(arr)); //[7, 9, 10, 11, 12, 25] /** * Further binary search * static int binarySearch(int[] a, int key) * Use the binary search method to search the specified int array to obtain the specified value. * static int binarySearch(int[] a, int fromIndex, int toIndex, int key) * Use the binary search method to search the range of the specified int array to obtain the specified value. * * Return value: * 1.If yes, the subscript is returned directly * 2.If not, and the element is greater than all the values in the array, the insertion point is the length of the array, and the subscript (- arr.length)-1 is returned * 3.If it does not contain, and the element is not greater than all values in the array, the insertion point is the subscript of the first element greater than key, and the subscript (- index)-1 is returned */ int index = Arrays.binarySearch(arr,8); System.out.println(index); } }
/** * Arrays Tool class deep iteration fill element */ public class ArraysDemo3 { public static void main(String[] args) { //deepToString deep iteration int[][] arr = {{1,2,3},{4,5,6,7}}; System.out.println(Arrays.toString(arr)); //address System.out.println(Arrays.deepToString(arr)); //The value of the element //static void fill(Object[] a, Object val) fill element String[] strs = new String[5]; Arrays.fill(strs,"aaa"); System.out.println(Arrays.toString(strs)); //[aaa,aaa,aaa,aaa,aaa] //static void fill(Object[] a, int fromIndex, int toIndex, Object val) specifies the range fill element Arrays.fill(strs,1,4,"bbb"); System.out.println(Arrays.toString(strs)); //[aaa,bbb,bbb,bbb,aaa] } }