第六章 一维数组及经典应用

第六章 一维数组及经典应用

1.数组

数组是一个变量,存储相同数据类型的一组数据

声明一个变量就是在内存空间划出一块合适的空间

声明一个数组就是在内存空间划出一串连续的空间

数组基本要素

标识符

数组元素

元素下标:从0开始

元素类型

数组中的所有元素必须属于相同的数据类型

使用数组四步走

1.声明数组 int[ ] a; 告诉计算机数据类型是什么

2.分配空间 a = new int[5]; 告诉计算机分配几个连续的空间

3.赋值 a [0] = 8; 向分配的格子里放数据

4.处理数据 a [0] = a[0] * 10

声明数组并分配空间

数据类型[ ]  数组名   =   new   数据类型[大小]  ;             

数组赋值

方法1: 边声明边赋值

int[ ] scores = {89, 79, 76};


int[ ] scores = new int[ ]{89, 79, 76};

方法2:动态地从键盘录入信息并赋值

Scanner input = new Scanner(System.in);
for(int i = 0; i < 30; i ++){
     scores[i] = input.nextInt();
}

处理数据

对数据进行处理:计算5位学生的平均分

int [ ] scores = {60, 80, 90, 70, 85};
double avg;
avg = (scores[0] + scores[1] + scores[2] + scores[3] + scores[4])/5
int [ ] scores = {60, 80, 90, 70, 85};
int sum = 0;
double avg;
for(int i = 0; i < scores.length; i++){
     sum = sum + scores[i];
}
avg = sum / scores.length; 

数组与内存

在这里插入图片描述

常见错误

public class ErrorDemo1 {
     public static void main(String[ ] args){
          int[ ] score = new int[ ];  编译出错,没有写明数组的大小
          score[0] = 89;
          score[1] = 63;
          System.out.println(score[0]);
    }
} 


int[ ] scores = new int[2];
scores[0] = 90;
scores[1] = 85;
scores[2] = 65;   编译出错,数组越界
System.out.println(scores[2]);

int[ ] score = new int[5];
       score = {60, 80, 90, 70, 85};
      
       int[ ] score2;
       score2 = {60, 80, 90, 70, 85}; 
 
编译出错,创建数组并赋值的方式必须在一条语句中完成

, 70, 85};

   int[ ] score2;
   score2 = {60, 80, 90, 70, 85}; 

编译出错,创建数组并赋值的方式必须在一条语句中完成


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值