javase数组的使用步骤

数组的使用步骤
(1) 声明数组:告诉计算机数据类型是什么
int[ ] score1; //Java成绩
int score2[ ]; //C#成绩
String[ ] name; //学生姓名
语法:
数据类型 数组名[ ] ;
数据类型[ ] 数组名 ;
(2) 分配空间:告诉计算机分配几个连续的空间
score = new int[30];
avgAge = new int[6];
name = new String[30];
语法:
数据类型[ ] 数组名=new 数据类型[大小];
(3) 赋值:向分配的空间里放数据
score[0] = 89;
score[1] = 79;
score[2] = 76;
……

此外也可以边声明边赋值:
int[ ] score = {89, 79, 76};

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

(4) 处理数组
取数组中的元素,求平均分:
int [ ] score = {60, 80, 90, 70, 85};
double avg;
avg = (score[0] + score[1] + score[2] + score[3] + score[4])/5;
结合循环:
数组的元素类型和数组的大小都是确定的,所以当处理数组元素时候,我们通常使用基本循环或者 For-Each 循环。
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};

  // 打印所有数组元素
  for (int i = 0; i < myList.length; i++) {
     System.out.println(myList[i] + " ");
  }
  // 计算所有元素的总和
  double total = 0;
  for (int i = 0; i < myList.length; i++) {
     total += myList[i];
  }
  System.out.println("Total is " + total);
  // 查找最大元素
  double max = myList[0];
  for (int i = 1; i < myList.length; i++) {
     if (myList[i] > max) max = myList[i];
  }
  System.out.println("Max is " + max);

}
}
以上实例编译运行结果如下:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值