Java初步认知和使用一维数组

为什么要使用数组

当你制定的同一类型的变量过多时,我们为了便于操作和管理,所以我们用到数组这个变量。

他其实就是一堆数据有序放置的组合。

什么是数组

1.数组申明

标识符

数组元素

元素下标

元素类型

元素类型 标识符[元素下标,从0开始]=

{数组元素,数组元素,数组元素(数组长度,当前为3)};

 

元素类型[元素下标,从0开始] 标识符=

{数组元素,数组元素,数组元素(数组长度,当前为3)};

 

例1:

intscores[]={1,2,3};  //数组长度3

int[]scores={1,2,3};  //数组长度3

stringscores[]={"asd","asd","asd","asd","asd"};  //数组长度5

string[]scores={"asd","asd","asd","asd","asd"};  //数组长度5

 

 

例2:

intscores[]=new  int[10];  //数组长度10

int[]scores=new  int[10];  //数组长度10

Stringscores[]=new String[20];   //数组长度20

String[]scores=new String[20];   //数组长度20

 

注意1:同一数组只能使用例1和例2申明的其中一种。

例如int scores[]={1,2,3}; int scores[]=new int[10];这样是错误的。

注意2:在申明的时候数组长度和数组元只能写一种。

例如int scores[3]={1,2,3}; int scores[]=new int[3] ={1,2,3};这样是错误的。

 

 

2.数组赋值

给数组赋值时必须写清楚数组的下标。

例如

intscores[]=new  int[10];

scores[0]=5;

scores[1]=5;

scores[0]=scores[0]*5;  

System.out.println(scores[0]+"\t"+scores[1]);

 

结果是:25    5

 

常见的运用

for循环加上键盘赋值运算

scannerinput=new Scanner(System.in);

intscores[]=new scores[10];

intnum=0;

for(inti=0;i< scores.length;i++){    //循环10次赋值

         scores[i]=input.nextint();     //用键盘赋值

         num+= scores[i];           //求数组数据之和

}

技巧1scores.length等于数组的长度可直接用来确定循环次数。

 

用强化for循环

scannerinput=new Scanner(System.in);

intscores[]=new scores[10];

intnum=0;

for(int score:scores){    //循环10次赋值

         num+= score;           //求数组数据之和

}

技巧:for(int score:scores)数组专用的强化for语句,表示每一次循环都会把数组scores的值从下标"0"开始,赋值给score

 

常见的错误

1.只要是申明与赋值和数组长度一起写的时候,赋值和数组长度必须写一个。

intscores=new scores[];                      (错误)

intscores=new scores[1];                            (正确)

intscores=new scores[]{1,2,3};    (正确)

 

2.数组越界

intscores=new scores[2];                           

scores[0]=1;

scores[1]=1;

scores[2]=1;

scores[3]=1;

分析:数组之申明了两个数据,所以不应该出现scores[2] 和scores[3],这属于数组越界。

 

3语法规定,申明和数组一次性全部赋值必须一条语句完成

intscores[];

scores={1,2,3};     (错误)

 

intscores[]={1,2,3}; (正确)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值