数组
1 定义:数组就是一个变量,存储相同数据类型的一组数据。
2 为什么需要数组?
在编程中定义一个数或者几个数很简单,但是当大量的数据出现,一个个定义过于繁琐,这个时候就需要用到数组。声明一个变量就是在内存空间划出一块合适的空间,声明一个数组就是在内存空间划出一串连续的空间。
3 数组的基本要素
标识符:数组的名称,用于区分不同的数组。
数组元素:向数组中存放的数据。
元素下标:对数组元素进行编号,从0开始,数组中的每个元素都可以通过下标来访问。
元素类型:数组元素的数据类型。
4 数组的使用步骤
(1)首先声明数组,告诉计算机数据类型是什么:
int[ ] score1; //Java成绩
int score2[ ]; //C#成绩
String[ ] name; //学生姓名
(2) 告诉计算机分配几个连续的空间
score = new int[30];
avgAge = new int[6];
name = new String[30];
(3) 向分配的空间里放数据
score[0] = 89;
score[1] = 79;
score[2] = 76;
……
此外也可以边声明边赋值:
int[ ] score = {89, 79, 76};
或者
int[ ] score = new int[ ]{89, 79, 76};
(4)处理数组
取数组中的元素,求平均分:
int [ ] score = {60, 80, 90, 70, 85};
double avg;
avg = (score[0] + score[1] + score[2] + score[3] + score[4])/5;
结合循环:使用基本循环或者 for…each 循环。
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// 计算所有元素的总和
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// 查找最大元素
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
以上实例编译运行结果如下:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
实例应用
计算10位学员的平均成绩
import java.util.Scanner;
public class ArrayDemo {
/**
* 使用数组计算平均分
*/
public static void main(String[] args) {
int[] scores = new int[10]; //成绩数组
int sum = 0; //成绩总和
Scanner input = new Scanner(System.in);
System.out.println("请输入10位学员的成绩:");
for(int i = 0; i < scores.length; i++){
scores[i] = input.nextInt();
sum = sum + scores[i]; //成绩累加
}
//计算并输出平均分
System.out.println("10位学员的平均分是:" + (double)sum/scores.length);
}
}