Seventh chapter (Array) Why do I need an array Java after the exam, the teacher assigned Zhang Hao a task to calculate the average of the class (30 people) of the int stu1=95; int stu2=95; int stu3=95; int stu4=95; {30 variables} int stu5=95; int stu6=95; int stu7=95; int stu8=95; int stun....=95; ..... 30 variables are too cumbersome to facilitate data processing. What is an array: An array is a variable that stores a set of data of the same data type int type variable: int=80; int type array: int=80; int =90; Int=n .... To declare a variable is to draw an appropriate space in the memory space to declare an array is to draw a string of contiguous space in the memory space what is an array. Array base feature identifier: The name of the array that distinguishes the different array elements: subscript The data elements that are stored in the array: numbering the elements of the arrays, starting with 0, each element in the array can access the element type by subscript: The data type of the array element Note: The array length is fixed to avoid array out of bounds. Summary: All elements in an array must belong to the same data type using an array of four steps: 1, declaration int[] A, 2, allocated space a = new int "5", 3, assignment a "0" = 8; 4, processing data a "0" =a "0" *10;① Declaration array: Tell the computer what the data type is int "" SCORE1;//java score int "" SCORE2;//c score String "" Name ;//Student name Syntax: 1 data type array name ""; 2 data type "" array name; Array length is not specified when declaring an array ② Matching space
Allocate space: Tell the computer to allocate several contiguous spaces
Socre =new int "30";
Avgage =new int "6";
Name =new String "30";
Syntax: declaring an array and allocating space
data type [] Array name = new data type [size];
③ assignment: Put data into the allocated grid ....
Score "0" = 89;
Score "0" = 89; {30 values are too troublesome! Can you assign a value together?
Score "0" = 76;
Method 1: Edge Declaration Edge Assignment
Int[] score={89,78,76};
Int[] Score=new int[]{89,88,99}; Note: You cannot specify an array length.
Method 2: Dynamically input information from the keyboard and assign values
Scanner input =new Scanner (system.in);
for (int i=0;i<30;i++) {
Score[i]=input.nextint ();
}
④ processing Data
Data processing: Calculates the average score for 5 students
Method 1:int[]score={60,80,78,88,97};
Double avg;
Avg= (Score[0]+score[1]+score[2]+score[3]+score[4])/5;
Method 2:int[]score={60,78,89,87,58};
int sum=0;
Double avg;
for (int i=0;i<score.length;i++) {
Sum=sum+score[i];
}
AVG = sum/score.length;
Ask for the best results
Max=scores[0];
for (int i=1;i<scores.length;i++) {
if (Scores[i]>max) {//Minimum value < (less than sign)
Max=scores[i];
}
}
System.out.println ("the highest test scores are divided into:" +max);
Java Chapter 7th