• 循环结构进阶


    一.什么是数组:

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

    声明一个变量就是在内存空间划出一块合适的空间
    声明一个数组就是在内存空间划出一串连续的空间

    二.数组基本要素:

    标识符:数组的名称,用于区分不同的数组
    数组元素:向数组中存放的数据
    元素下标:对数组元素进行编号,从0开始,数组中的每个元素都可以通过下标来访问
    元素类型:数组元素的数据类型

    注意:数组长度固定不变,避免数组越界

    三:使用数组的步骤:

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

    语法:
    数据类型 数组名[ ] ;
    数据类型[ ] 数组名 ;


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

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


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

    3.1 边声明边赋值
    int[ ] score = {89, 79, 76};
    int[ ] score = new int[ ]{89, 79, 76}; 不能指定数组长度

    3.2 动态地从键盘录入信息并赋值
    Scanner input = new Scanner(System.in);
    for(int i = 0; i < 30; i ++){
    score[i] = input.nextInt();
    }

    4.处理数据:计算5位学生的平均分 a[0]=a[0]*10;
    int [ ] score = {60, 80, 90, 70, 85};
    double avg;
    avg = (score[0] + score[1] + score[2] + score[3] + score[4])/5;

    数组名.length代表数组的长度

    案例:计算全班学员的平均分

    public class Demo01 {
    public static void main(String[] args) {
    //存储30名学员的成绩
    int [] score=new int[5];
    double avg=0.0; //平均分
    double sum=0; //成绩总和
    Scanner input=new Scanner(System.in);
    //.length:代表了数组的长度 30

    for (int i = 0; i < score.length; i++) {
    System.out.println("请输入第"+(i+1)+"位学员的成绩:");
    score[i]=input.nextInt();
    //每一次循环计算总和
    sum=sum+score[i];
    }
    avg=sum/score.length;
    System.out.println("平均分:"+avg);


    }
    }

    四.数组排序:
    升序:Arrays.sort(数组名); 从0到最大
    降序:升序拍列完毕后 从最大到0
    案例:升序he降序拍列成绩
    public class Demo02 {
    public static void main(String[] args) {
    //定义一个数组,存储5位学员的成绩
    int [] score=new int[]{98,56,74,85,100};
    System.out.println("5位学员的初始成绩:");
    for (int i = 0; i < score.length; i++) {
    System.out.print(score[i]+" ");
    }
    System.out.println();
    System.out.println("5位学员的升序拍列后的成绩:");
    //升序拍列
    Arrays.sort(score);
    for (int i = 0; i < score.length; i++) {
    System.out.print(score[i]+" ");
    }
    System.out.println();
    System.out.println("5位学员的降序拍列后的成绩:");
    //降序:从后往前打印
    //score.length-1:数组最大下标
    for (int j = score.length-1; j>=0; j--) {
    System.out.print(score[j]+" ");
    }

    }
    }

  • 相关阅读:
    20200816
    20200815
    20200813
    20200811
    20200810
    20200806
    20200804
    20200803
    20200802
    20200801
  • 原文地址:https://www.cnblogs.com/rzbwyj/p/9066858.html
Copyright © 2020-2023  润新知