The article directories

  • 1. Why do we need arrays
    • 1.1 Introduction to Arrays
    • 1.2 Arrays Quick Start
  • 2. Use of arrays
    • 2.1 Dynamically Initializing an Array
    • 2.2 Statically initializing arrays
  • 3. Notes and details of using arrays
  • 4. Application cases of arrays

1. Why do we need arrays

  • A chicken farm has six chickens whose weights are respectively3 kg, 5 kg, 1 kg, 3.4 kg, 2 kg, 50 kg. What is the total weight of these six chickens? What is the average weight? Please make up a program. Array01.java
  • Define 6 variables, add up the total weight, and calculate the average weight. Leads to -> array

1.1 Introduction to Arrays

  • Arrays can hold multiple pieces of the same type of data. An array is also a data type, a reference type. A group of numbers is a group of data

1.2 Arrays Quick Start

Array01.java

  • For example, we could solve the previous problem with arrays.
  • Analysis of ideas:
  1. We can get throughHens (subscript)To access the elements of the array, subscript from0So the first number like the first element is going to behens[0]And the second element is going to behens[1]And so on
  2. throughforI can loop through the arrayElements/value
  3. Use a variabletotalWeightTake the elementsThe cumulative
	double[] hens = {3.5.1.3.4.2.50};
	double totalWeight = 0;
	for (int i = 0; i < 6; i++) {
	    System.out.println("The first" + (i+1) + "The value of each element =" + hens[i]);
	    totalWeight += hens[i];
	}
	System.out.println("Total weight =" + totalWeight + "Average weight =" + (totalWeight / hens.length));
Copy the code
  • Because the array is from0The initial subscript, soforIn a loopi = 0Indicates that the array subscript has0,1,2,3,4,56Three elements can be traversed (because there are elements in the array6), so I < 5 (equivalent to having6Element) can also be written asi <= 5For clarity, it is usually written asi < 6

  • If you want to increase the number of chickens, you just change the array, nothing else needs to be changed.

2. Use of arrays

  • steps
  1. Create an array of doubles of size 5

(1) The first dynamic allocation method

	double scores[] = new double[5];
Copy the code

(2) The second dynamic allocation method, first declare the array, and then new allocation space

	double scores[] ; // Declare an array, scores is null
	scores = new double[5]; // Allocate memory space for storing data
Copy the code
  1. Loop input
Scores. Length indicates the size/length of the arrayCopy the code
	double[] scores = new double[5];
	Scanner sc = new Scanner(System.in);
	for (int i = 0; i < scores.length; i++) {
	    System.out.println("Please enter no" + (i + 1) + "The values of the elements");
	    scores[i] = sc.nextDouble();
	}
	System.out.println("== array element output: ==");
	for (int i = 0; i < 5; i++) {
	    System.out.println("Please enter no" + (i + 1) + "The values of the elements" + scores[i]);
	}
Copy the code

2.1 Dynamically Initializing an Array

  • Let’s declare an array

    Grammar:Data type array name []; Data type [] array name;
inta[]; orint[] a;
Copy the code
  • Create an array

    Grammar:Array name =new data type [size];
a=new int[10];
Copy the code
  • Case presentation

2.2 Statically initializing arrays

3. Notes and details of using arrays

  1. An array is a combination of multiple data of the same type to achieve unified management of these data
int[] arr1 = {1.2.3.60."hello"};//String ->int type mismatch
double[] arr2 = {1.1.2.2.3.3.60.6.100};//int ->doubl can be passed to satisfy automatic type conversion
Copy the code
  1. The elements of an array can be any data type, including primitive and reference types, but cannot be mixed.
String[] arr3 = {"Beijing"."jack"."milan}
Copy the code
  1. After the array is created, there is a default value if no value is assigned
int 0.short 0.byte 0.long 0.float 0.0.double 0.0.char\ u0000,boolean falseThe Stringnull
Copy the code
  • For example:
	short[] arr4 = new short[3];
	System.out.println("= = array arr4 = =");
	for (int i = 0; i < arr4.length; i++) {
	    System.out.println(arr4[i]);
	}
Copy the code

  1. The steps to use an array are as follows: 1. Declare the array and create space 2. Assign values to each element of the array 3. Use an array
  2. The index of the array starts at 0.
  3. Array subscripts must be used within the specified range, otherwise:Subscript out-of-bounds exception, such as

    int [] arr=new int[5];Then the effective subscript is0 to 4, that is, the minimum subscript of the array is0And the maximum isArray length -1(5-1 = 4)
  4. Array genus reference type, array data is object (object)

4. Application cases of arrays

  1. Create an array of 26 elements of type char and place them separately'A'-'Z'. Use the for loop to access all the elements and print them out. Tip: Char data operations'A'+2 -> 'C'

    ArrayExercise01.java
  • Thought analysis

    1. Define an arraychar[] chars = new char[26]

    Because 2.'A' + 1 = 'B'And so on, so for is used to assign

    3. Use the for loop to access all elements
	char[] chars = new char[26];
	for( int i = 0; i < chars.length; i++) {// Loop 26 times
		/ / chars is char []
		/ / chars [I] is char
		chars[i] = (char) ('A' + i); //'A' + I is int and needs to be cast
	}
	
	// Loop output
	System.out.println("= = = = = = chars array");
	for( int i = 0; i < chars.length; i++) {// Loop 26 times
		System.out.print(chars[i] + "");
	}
Copy the code

  1. Request the maximum value of int[] {

    4,-1,9, 10,23} and get the corresponding subscripts. ArrayExercise02.java

  • Thought analysis
  1. Define an int arrayInt [] arr = {4,-1,9, 10,23};
  2. Assume thatmax = arr[0]Is the maximum,maxIndex=0;
  3. From the subscript1To traverse thearrIf theMax < current element,maxIt’s not really the maximum. We just

    Max = current element; MaxIndex = index of the current element
  4. As we iterate through this arrayarrLater,maxThat’s the true maximum,maxIndexThe subscript of the maximum value
	int[] arr = {4, -1.9.10.23};
	int max = arr[0];// Assume that the first element is the maximum
	int maxIndex = 0; //
	
	for(int i = 1; i < arr.length; i++) {// iterate over arr from subscript 1
	
		if(max < arr[i]) {// If Max < current element
			max = arr[i]; // Set Max to the current elementmaxIndex = i; }}// When we iterate through the array arr, Max is the actual maximum value, maxIndex
	System.out.println("max=" + max + "" + "maxIndex=" + maxIndex);
Copy the code