java一维数组

java基础中一维数组及应用

1:为什么需要数组?

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

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

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

2:如何使用数组?

使用数组四步骤

1.声名数组   int[ ] a;

2.分配数组  a = new int [ ] ;

3.赋值     a[ ] = 8;

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

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

int[ ] score1;             //Java成绩

int score2[ ];             //C#成绩

String[ ] name;        //学生姓名

声明数组时不规定数组长度   

4:分配空间: 告诉计算机分配几个连续的空间

scores = new int[30];

avgAge = new int[6];    

name = new String[30];

声明数组并分配空间 :         数据类型[ ]  数组名   =   new   数据类型[大小]  ; 

数组元素根据类型不同,有不同的初始值   int--o    double--o.o   string--nu||

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

scores[0] = 89;

scores[1] = 79;

scores[2] = 76; ……太麻烦

方法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:处理数据   对数据进行处理:计算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; 

for(int score:scores){   

 sum += score;

}

avg = sum / scores.length; 

 // 声明数组 并且给数组分配内存空间
        int [] scores  =  new int[5];
        
        Scanner input=new Scanner(System.in);
        
        // 给数组元素赋值 (i=0 ===>  i=4)
        for(int i=0;i<=4;i++){
            System.out.println("请输入学生的成绩:");
            int temp=input.nextInt();
            scores[i]=temp;
        }
        
        // 遍历数组中的元素   // 0 --> 4
        for(int i=0;i<=4;i++){
            System.out.println("第"+(i+1)+"个学生的成绩:"+scores[i]);
        }
        
    }
}

/**
 * 
 * @author Administrator 定义数组保存5个学生的成绩(整数)
 */
public class Demo2 {
    // 元素类型
    // 数组标识符(变量名)
    // 数组的元素(数组中需要保存的值)
    // 数组元素的下标

    // 数组: 存储一组相同类型的数据。
    public static void main(String[] args) {
        // 声明数组
        int[] scores;
        // 分配空间
        scores = new int[5];
        // 赋值
        scores[0] = 100;
        scores[1] = 100;
        scores[2] = 100;
        scores[3] = 100;
        scores[4] = 100;
        // 处理数据
        scores[0] = scores[0] - 20;
        //输出
        System.out.println("第一个学生的成绩是:"+scores[0]);
        System.out.println("第二个学生的成绩是:"+scores[1]);
        
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扶小一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值