preface

C: A loop is a small hole in Java syntax that we will soon get out of the way of syntax entry.

In this article, Teacher Cha will take you to learn an advanced knowledge of Java syntax introduction, data structure: array.

In the Java knowledge we have learned so far, if we want to use the program, store a score data, as shown below.

// Declare a variable to store results
double score = 90;
Copy the code

But when we store and use five, ten, or more score data, the efficiency and usability of variables as a single store becomes less friendly.

double score1 = 90;
double score2 = 80;
double score3 = 70;
double score4 = 60;
double score5 = 59; .Copy the code

So we need a more advanced storage method that can store multiple data simultaneously and is easy to use.

Data Structure Overview

Before we start introducing arrays, let’s introduce the basic concepts of data structures.

Data structures are the way computers store and organize data.

A data structure is a collection of data elements that have one or more specific relationships with each other. More often than not, a carefully chosen data structure can lead to higher running or storage efficiency. Data structures are often associated with efficient retrieval algorithms and indexing techniques. [1]

There are many kinds of data structures. Generally speaking, according to the logical structure of data, it is simply classified, including linear structure (linear table) and nonlinear structure (nonlinear table). [2]

  1. A Linear List is a List in which nodes have a Linear relationship. The data row forms a linear structure. [3]

    Common linear table data structures are: arrays, queues, stacks, linked lists, etc.

  2. A nonlinear table is one in which there are multiple relationships between nodes. [2]

    Common nonlinear table data structures are: tree, graph, etc.

Mr. Zha said: Data structure is a very important basic subject in the computer department. The purpose of data structure is to make the computer can store and use data in a more simple, efficient and convenient way.

Summary of array

Array is the most basic and typical sequential structure in linear data structure. It uses a contiguous set of memory Spaces to store a set of data of the same type. [3]

Let’s compare variables with arrays:

  • Variable: Is to carve out a suitable space in memory.
  • Array: A string of contiguous Spaces in memory.

An array of

Let’s also compare the components of a variable to an array.

variable An array of
A variable’s value Array element: Data stored in an array
Variable data type The type of an array element: All data stored in an array must be of the same data type
The variable name An array of: Used to distinguish different arrays. The naming conventions are the same as the variable names
Array capacity: How many elements can be stored in an array
Array subscript/indexAn array is a sequence of contiguous Spaces, each with a corresponding “number”,Count from 0

More Actions Variable Array variable value Array element: Data stored in an array Variable Data type Type of an array element: All data stored in an array must be of the same data type Variable name Array name: Used to distinguish different arrays, naming conventions are the same as variable names Array capacity: How many elements can be stored in an array Array subscript/index: An array is a sequence of contiguous Spaces, each with a corresponding “number”, counting from 0

The subscript of an array is determined by its size (length). If the size of the array is 5, the subscripts of the array are 0, 1, 2, 3, 4. Once an array size is defined, it cannot be changed.

To define an array

Now that we know what an array is, let’s define an array ourselves to use. In Java, arrays can be defined in a very flexible way. there are two common ways to define arrays.

Methods a

The first way to define an array is to declare the array and then assign a value to it.

// Declare array syntaxData type [] Array name =newData type [array size];Copy the code
// Array assignment syntaxArray name [subscript] = element value;Copy the code

This is the most traditional way to define an array. By specifying the type of data and the size of the array, a string of contiguous Spaces can be used to store data.

The syntax of the array declaration is similar to that of the variable definition, except that there is a new keyword. This keyword is also used in the Scanner.

Okay, back to the requirements we mentioned in the introduction, and implement them using method one.

Example Requirements: Store the grades of 5 students in the class, the grades are: 90, 80, 70, 60, 50.

Analysis of ideas:

  1. Depending on your requirements, arrays are more appropriate for multiple data stores
  2. Determine the components of the array
    1. Array element: result
    2. Array element type: double
    3. Array name: scores (scores are usually named score, and scores are plural: scores)
    4. Array size (determine subscript) : 5
  3. According to the composition of the array, the implementation of the array syntax
// Declare an array of length 5 to store data of type double
double[] scores = new double[5];

// Assign to the array
// assign 90 to the first space in the array
scores[0] = 90;
// assign 80 to the second space in the array
scores[1] = 80;
// assign 70 to the third space of the array
scores[2] = 70;
// assign 60 to the fourth space of the array
scores[3] = 60;
// assign 50 to the 5th space of the array
scores[4] = 50;
Copy the code

Store the data, when using the data, also need to use the array name and array subscript to carry out.

// Use syntax: array name [subscript]
System.out.println(scores[0]); / / 90.0
Copy the code

The subscript is counted from 0, so it is extremely easy to use the array beyond the size range. For example, scores[5] = 40;

And this kind of problem, at compile time does not report the error, only at run time report the error (array out of bounds exception), you need to be more careful, repeatedly with comments and other ways to remind yourself.

Way 2

Method 1 is defined in such a way that an array is declared and then assigned. If you want to get an assigned array quickly, you can use the following syntax to do so.

// Assign when declaring an array
/ / grammarData type [] Array name = {element1Elements,2. };Copy the code

This definition is ideal for quickly defining a valued array. There is no need to specify the capacity, the array will specify the capacity based on the number of elements.

Let’s modify the requirement implementation using method two syntax.

double[] scores = {90.80.70.60.50};
Copy the code

When you declare an array, you can also write it like this.

// Assign when declaring an array
/ / syntax:Data type [] Array name =newData type [] {element1Elements,2. };Copy the code

Let’s re-engineer the requirement implementation.

// Note: if there is [], you do not need to specify the size of the array. It is empty
double[] scores1 = new double[] {90.80.70.60.50};
Copy the code

Teacher Zha said: there must be some students will ask: this definition method, and the above is almost the same, what is the use of learning? Don’t worry, this may be your only and better choice for using arrays in future chapters.

The default value for the array

In the old days, we declared a local variable, and if we didn’t assign a value, we couldn’t use it. Once you’ve declared the array, if you just use it without any assignment, you’ll find that every space in the array has a value.

This is because an array declaration is accompanied by an initialization action, which is the process of setting a default value for each space in the array based on the array element data type.

  • Arrays of integers (byte, short, int, long) : The default value is 0
  • Floating-point arrays (float, double) : Default is 0.0
  • Boolean array (Boolean) : Default is false
  • Char: Default is a space (\u0000)
  • String arrays: The default value is null

Null is a special value, which we will refer to later when we talk about referencing data types.

double[] dArr = new double[5];
System.out.println(dArr[0]); / / 0.0

int[] iArr = new int[5];
System.out.println(iArr[0]); / / 0

boolean[] bArr = new boolean[5];
System.out.println(bArr[0]); // false

char[] cArr = new char[5];
System.out.println(cArr[0]); // a space, \U0000

String[] sArr = new String[5];
System.out.println(sArr[0]); // null
Copy the code

Dynamic assignment

In method one assignment, those of us who have studied loops will soon find some repetitive, regular operations.

If we combine this with Scanner typing, we can make the array assignment dynamic.

Analysis of ideas:

  1. According to the analysis of the effect drawing, there is only a single law, and a single layer of circulation can be used
  2. Identify cycle elements
    1. Cyclic conditions:< array length
    2. Loop: array name [loop variable] = input element value;
  3. Fixed times loop, use for loop
  4. Check that the loop exits properly
// Declare an array to store 5 student scores
double[] scores = new double[5];

// Dynamic entry of student scores
Scanner input = new Scanner(System.in);
// Array name. length can get the capacity of the array
for (int i = 0; i < scores.length; i++) {
    System.out.print("Please enter no" + (i+1) + "Student scores:");
    scores[i] = input.nextDouble();
}

System.out.println("No. 3 Student result:" + scores[2]);
Copy the code

Array traversal

In the realization of dynamic assignment, we skillfully use the loop to realize the rule of array assignment. In fact, the same rule still applies to evaluating from an array. Among the common operations on arrays, a concept called traversal often pops up.

Traversal: The process of pulling out the elements of an array one by one.

Now, let’s see how we can do array traversal.

Loop subscript traversal

The most common way to iterate is by iterating through an array of subscripts. That’s the loop we just used for dynamic assignment.

// Define an array
double[] scores = {90.80.70.60.50};

// Loop all subscripts, and then evaluate according to the subscripts
for (int i = 0; i < scores.length; i++) {
    // Array name [loop subscript]
    System.out.println(scores[i]);
}
Copy the code

The forEach traversal

In addition, there is a more unusual way to iterate: through forEach loops (commonly known as enhanced for loops). The main emphasis of this traversal is to take the elements out of the array one by one, each time temporarily stored in a variable.

// Declare an array and assign a value
double[] scores = {90.80.70.60.50};

// for (array element data type variable name: array name to iterate over)
// Score is a variable that temporarily stores each element in a loop
for (double score : scores) {
    System.out.println(score);
}
Copy the code

Teacher Zha said: compared with cyclic subscript traversal, enhanced for loop traversal is easier to use, but it may not be easy to understand in the early stage. If it is really difficult to understand, we should use cyclic subscript traversal first. And sometimes, when we need subscripts as an auxiliary factor, it’s more convenient to use cyclic subscript traversal.

Using an array

Let’s use arrays to solve some requirements.

Print consumption records

Case requirements: Implement according to the effect drawing, and print the member consumption list.

// Declare an array of length 5 to store this month's consumption records
double[] records = new double[5];

// Dynamic assignment
Scanner input = new Scanner(System.in);
System.out.println("Please input the member's consumption record for this month:");
for (int i = 0; i < records.length; i++) {
    System.out.print("Please enter no" + (i+1) + Amount of purchase:);
    records[i] = input.nextDouble();
}

System.out.println();

// Declare variables to store the total amount of consumption
double sum = 0;
System.out.println("Serial number \t\ T Amount (YUAN)");
for (int i = 0; i < records.length; i++) {
    System.out.println((i+1) + "\t\t" + records[i]);
    sum += records[i];
}
System.out.println("Total amount \t\t" + sum);
Copy the code

Guess the number

Example requirement: there is one sequence: 8,4,2,1,23,344,12.

  1. Loop over the value of the sequence
  2. Find the sum of all values in a sequence
  3. Guess the number of games: from the keyboard arbitrary input a data, determine whether the sequence contains this number

Both ways of traversing the array are used.

// Declare an array, store the values of the array
int[] numArr = {8.4.2.1.23.344.12};

// 1. Loop out the values of the array
System.out.println("The values in the sequence are:");
for (int num : numArr) {
    System.out.println(num);
}
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

// 2. Find the sum of all values in the sequence
int sum = 0;
for (int i = 0; i < numArr.length; i++) {
    sum += numArr[i];
}
System.out.println("The sum of all values of the sequence is:" + sum);
System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");

// 3. Guess the number game: input any data from the keyboard to determine whether the number is included in the sequence
3.1 Enter any data from the keyboard
Scanner input = new Scanner(System.in);
System.out.print("Please enter a value:");
int num = input.nextInt();

// 3.2 Check whether the number is included in the sequence
/ / sign
boolean flag = false; // Assume the array does not contain this value
for (int i = 0; i < numArr.length; i++) {
    if (numArr[i] == num) {
        flag = true;
        break; }}// 3.3 Determine the flag bit
if (flag) {
    System.out.println("This value is included in the sequence!");
} else {
    System.out.println("This value is not included in the sequence!");
}
Copy the code

Strives for the highest score

Case requirements: input the scores of five students in the Java exam from the keyboard to get the highest score.

Fight in a ring.

Wuxia TV series, often staged “wen no first, wu no second” drama. Competition or martial arts meeting: at the beginning, there is a champion, then there are all the major chivalric warriors compete against each other, the winner will become the new champion, and so on the end of the remaining is the strongest.

// 1. Input the scores of the five students in the Java exam
double[] scoreArr = new double[5]; 

Scanner input = new Scanner(System.in);
for (int i = 0; i < scoreArr.length; i++) {
    System.out.print("Please enter no" + (i + 1) + A student's score:);
    scoreArr[i] = input.nextDouble();
}

// 2
// Assume a maximum score (assume a data from the data to be compared)
double max = scoreArr[0];
for (double score : scoreArr) {
    // If there is a value greater than Max in the comparison process
    // Change the value of Max to the latest value
    if (score > max) {
        max = score;
    }
}
System.out.println("Highest score:" + max);
Copy the code

For the lowest price

Case requirements: Input the OnePlus 8T price of 4 mobile phone stores, output which store has the lowest price and the lowest mobile phone price.

This is the same idea as the last problem, so let’s implement it.

// Declare an array to store the phone prices of 4 stores
double[] prices = new double[4];

// Dynamic assignment
Scanner input = new Scanner(System.in);
System.out.println("Please enter the price of OnePlus 8T phone in 4 stores:");
for (int i = 0; i < prices.length; i++) {
    System.out.print("The first" + (i+1) + "The price of a home store:");
    prices[i] = input.nextDouble();
}

// Declare the variable, assuming the lowest price is the first one
double min = prices[0];
// Declare a variable, store the lowest price is the number
int minStore = 1;
for (int i = 0; i < prices.length; i++) {
    // If there is one lower than the lowest price
    if (prices[i] < min) {
        // Change the lowest price
        min = prices[i];
        // Switch to the lowest price store
        minStore = i + 1;
    }
}
System.out.println("The first" + minStore + "Home has the lowest price and the price is:" + min);
Copy the code

reference

[1] Peng Jun, Xiang Yi. Data Structure Budget Law: Posts and Telecommunications Press, 2013

[2] Liu Yadong; Qu Xinhui. Handbook of C/C++ Common Algorithms: China Railway Publishing House, 2017.09: page 21

[3] Feng Xiaoyuan. An array of data structures [EB/OL]. HTTP: / / www.cnblogs.com/fengxiaoyua… . 2019-05-27

Afterword.

Well, the introduction of one-dimensional array is over here, this homework please search wechat attention: check the teacher’s handout, and then reply to one-dimensional array homework can be.

With the array data structure, it is easier to store and use multiple data, which leads to the unlocking of some algorithm-based questions. In this assignment, Mr. Cha has compiled more than 10 exercises, hoping that you can practice your logical thinking by solving these problems.

Don’t worry if you can’t do it. You can also comment and ask Teacher Zha to give you reference answers.

Finally, keep in mind the reason we’re learning about arrays: Because the previous data storage methods are no longer adequate for our increasingly complex needs. Moreover, array, as a typical, basic linear table data structure, has its advantages in storage.

Because of the existence of subscripts, its efficiency is relatively good, so it is suitable for the scenes with less addition and deletion and more data retrieval. However, it has a disadvantage: it can only store a set of data of the same data type of fixed length.

Teacher Zha said: For the learning of technology, teacher Zha has always followed the following steps: With a simple demo to let it run first, and then learn it the most commonly used API and configuration can let yourself up, finally, on the basis of proficiency in the spare time reading the source to try to make myself to be able to see clearly its running mechanism, part of the cause of the problem, at the same time, draw lessons from these technology to enhance your own code level.

So in the teacher’s article, the early basic are small white, only interspersed with a very small amount of source research. Of course, such as the small white update, you still like, the late will not regularly dedicated to part of the technology of the source code analysis.