文档详情

Java语言程序设计讲义数组与字符串.ppt

发布:2025-04-02约3.3千字共25页下载文档
文本预览下载声明

《Java语言程序设计(一)》串讲

第四章数组和字符串

本章重点

数组的应用

字符串常用方法

字符串与基本类型数据之间的转换

数组定义

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

int类型

元素

博物架名

标识符

古玩

物品编号

元素下标

物品类型

元素类型

数据

使用数组四步走:

1、声明数组

2、分配空间

3、赋值

4、处理数据

如何使用数组

int[]a;

a=newint[5];

a[0]=8;

a[0]=a[0]*10;

a

8

80

a[0]

数组的声明

声明数组:告诉计算机数据类型是什么

1

数据类型数组名[];

数据类型[]数组名;

数组初始化

score=newint[30];

avgAge=newint[6];

name=newString[30];

30

……

分配空间:告诉计算机分配几个格子

数组属于引用数据类型

2

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

声明数组并分配空间

数组赋值

score[0]=89;

score[1]=79;

score[2]=76;

……

赋值:向分配的格子里放数据

……

30

score[0]

score[1]

score[2]

89

79

76

太麻烦!能不能一起赋值?

3

数组赋值

方法1:边声明边赋值

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

解决

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

Scannerinput=new);

for(inti=0;i30;i++){

score[i]=();

}

int[]score=newint[]{89,79,76};

使用数组求平均值

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

doubleavg;

avg=(score[0]+score[1]+score[2]+score[3]+score[4])/5;

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

intsum=0;

doubleavg;

for(intindex=0;index;index++){

sum=sum+score[index];

}

avg=sum/;

成绩单

访问数组成员:使用“标识符[下标]”

访问成员

数组的length属性

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

4

publicclassHelloAccp2{

publicstaticvoidmain(String[]args){

int[]score=newint[];

score[0]=89;

score[1]=63;

System.out.println(score[0]);

}

}

常见错误

编译出错,没有写明数组的大小

publicclassHelloAccp3{

publicstaticvoidmain(String[]args){

int[]score=newint[2];

score[0]=89;

score[1]=63;

score[2]=45;

System.out.println(score[2]);

}

}

常见错误

编译出错,数组越界

常见错误

publicstaticvoidmain(String[]args){

int[]score=newint[5];

score={60,80,90,70,85};

int[]score2;

score2={60,80,90,70,85};

}

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

数组

一维数组由一列相同类型的数据组成

可以通过指定数组的名称和大小来声明数组

一维数组

多维数组

多维数组是数组的数组

要声明一个多维数组,必须

使用另一组方括号来指定附

显示全部
相似文档