Java数组一

数组

一:数组的定义

1:什么是数组

数组是具有相同数据类型且按一定次序排列的一组变量的集合体。即用一个变量名表 示一批数据。

2:什么是数组下标

下标就是数组元素在数组中的位置。下标从0开始,依次累加1,也 称为数组索引。

3:所以数组的步骤

(1)定义数组

第一种:数据类型 数组名[];  eg:int scores[];
第二种:数据类型[] 数组名;  eg:int[] scorces;

(2)为数组元素分配内存

数组名 = new 数据类型[数据长度]; eg:scores[] = new int[5];
(1)和(2)写一起为:int[] scores = new int[5] 

(3)数组元素初始化

288bf06a0f5599c3b49ba235b6b1813

(1)(2)(3)和在一起为  int[] scores = new int[]{值};

(4)使用数组

例题:求最小值

public class Main {
    public static void main(String[] args) {
        int[] scores  ={8,7,9,2,0,5,6};
        int min = scores[0];
        for (int i = 0;i < scores.length;i ++){
            if(min > scores[i]){
                min = scores[i];
            }
        }
        System.out.println("最小值是:"+ min);
    }
}

求和

public class Main4 {
    public static void main(String[] args) {
        int[]  scores = {8,6,9,3,2,1,5,4};
        int sum = 0;
        for (int i = 0; i < scores.length;i ++){
          sum += scores[i];
        }
        System.out.println("和是" + sum);
    }
}

求遍历数组元素

public class Main3 {
    public static void main(String[] args) {
        double[] scores = new double[10];
​
        Scanner src = new Scanner(System.in);
        for (int i = 0; i < scores.length; i++) {
​
            System.out.printf("请输入%d位同学的考试成绩", i + 1);
            scores[i] = src.nextDouble();
        }
        //遍历数组
        for (int i = 0; i < scores.length; i++) {
            System.out.println(scores[i] + "\t");
        }
    }
​

二:生成随机数的方法

1:Math.random

public class Demo8 {
    public static void main(String[] args) {
        for(int i = 0;i < 10;i ++){
            System.out.println((int)(Math.random() * 40 + 1));
        }
    }
}

2:Random(需要倒入Random类)

import java.util.Random;
​
/**
 * 用Random生成随机数
 */
public class Demo9 {
    public static void main(String[] args) {
        Random random = new Random();
        for(int i = 1;i < 10; i ++){
            System.out.println(random.nextInt(4,8) + 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值