第数组与字符串.pptxVIP

  • 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

文档评论(0)

1亿VIP精品文档

相关文档