- 1
- 0
- 约4.58千字
- 约 24页
- 2022-09-07 发布于上海
- 举报
数组定义
67
64
79
89
95
数组是一个变量,存储相同数据类型的一组数据
int类型
元素
博物架名
标识符
古玩
物品编号
元素下标
物品类型
元素类型
数据
第1页/共24页
使用数组四步走:
1、声明数组
2、分配空间
3、赋值
4、处理数据
如何使用数组
int[ ] a;
a = new int[5];
a [0] = 8;
a [0] = a[0] * 10;
a
8
80
a[0]
第2页/共24页
数组的声明
int[ ] score1; //Java成绩
int score2[ ]; //C#成绩
String[ ] name; //学生姓名
声明数组: 告诉计算机数据类型是什么
1
数据类型 数组名[ ] ;
数据类型[ ] 数组名 ;
第3页/共24页
数组初始化
score = new int[30];
avgAge = new int[6];
name = new String[30];
30
……
分配空间: 告诉计算机分配几个格子
2
数据类型[ ] 数组名 = new 数据类型[大小] ;
声明数组并分配空间
第4页/共24页
数组赋值
score[0] = 89;
score[1] = 79;
score[2] = 76;
……
赋值:向分配的格子里放数据
……
30
score[0]
score[1]
score[2]
89
79
76
太麻烦!能不能一起赋值?
3
第5页/共24页
数组赋值
方法1: 边声明边赋值
方法2:动态地从键盘录入信息并赋值
解决
int[ ] score = {89, 79, 76};
Scanner input = new Scanner(System.in);
for(int i = 0; i 30; i ++){
score[i] = input.nextInt();
}
int[ ] score = new int[ ]{89, 79, 76};
第6页/共24页
使用数组求平均值
60
80
90
70
85
int [ ] score = {60, 80, 90, 70, 85};
double avg;
avg = (score[0] + score[1] + score[2] + score[3] + score[4])/5;
int [ ] score = {60, 80, 90, 70, 85};
int sum = 0;
double avg;
for(int index = 0; index score.length; index++){
sum = sum + score[index];
}
avg = sum / score.length;
成绩单
访问数组成员:使用“标识符[下标]”
访问成员
对数据进行处理:计算5位学生的平均分
4
第7页/共24页
public class HelloAccp2{
public static void main(String[ ] args){
int[ ] score = new int[ ];
score[0] = 89;
score[1] = 63;
System.out.println(score[0]);
}
}
常见错误
编译出错,没有写明数组的大小
第8页/共24页
public class HelloAccp3{
public static void main(String[ ] args){
int[ ] score = new int[2];
score[0] = 89;
score[1] = 63;
score[2] = 45;
System.out.println(score[2]);
}
}
常见错误
编译出错,数组越界
第9页/共24页
常见错误
public static void main(String[ ] args){
int[ ] score = new int[5];
score = {60, 80, 90, 70, 85};
int[ ] score
您可能关注的文档
最近下载
- 全国大学生数学建模竞赛b题全国优秀论文.docx VIP
- 全国大学生数学建模竞赛b题全国优秀论文 .pdf VIP
- 2026浙美版美术八年级下册第二单元第3课《独特的视角》课件.pptx
- 2023年全国大学生数学建模竞赛题目B:.docx VIP
- 2020年美国大学生数学建模竞赛题目E--淹没在塑料中范文五篇(含源代码).pdf VIP
- 2021年全国大学生数学建模竞赛题目E:中药材的鉴别优秀论文范例两篇(含源代码).pdf VIP
- 2025-《期货基础知识》教材精讲班.pdf VIP
- 农贸市场改造升级策略及实施方案.docx VIP
- 高中英语单词表(全)(最新完整版)11802.xls VIP
- 比亚迪E5汽车驱动电机异响故障检修方案设计.docx VIP
原创力文档

文档评论(0)