Java-一维数数组(Array)

一.什么是数组

        数组是一个固定长度的存储相同数据类型的数据结构,数组中的元素被存储在一段连续的内存空间中。 

                            

二.定义方式

//第一种:给每个空间分配值
int[] a = {1,2,3,4};
//第二种: 动态赋值,空间给定,默认给值:0
int[] b = new int[5];
//第三种: 综合式
int[] c =new int[]{1,2,3,4};

三.数组的使用

1.访问数组

       根据数组的下标进行访问,最大访问为  数组长度-1 (原因:数组的下标是从0开始)。


public class Test {
    public static void main(String[] args) {
        int[] array = {1,2,3,4,5};
        System.out.println(array[3]);
    }
}

2.遍历数组

方法一:for循环

public class ArrayDemo {
    public static void main(String[] args) {
        int []array = {1,2,3,4,5};
        for(int i=0;i<array.length;i++){
            System.out.print(array[i]+"\t");
        }
    }
}

运行结果:

方法二:foreach(加强性for循环)

package Test;

public class ArrayDemo {
    public static void main(String[] args) {
        int []array = {1,2,3,4,5};
        for(int x:array){
            System.out.print(x+"\t");
        }
    }
}

运行结果:

forach的介绍:

        foreach是一种循环遍历数组或集合的语法糖,它可以用来简化代码,提高可读性。foreach 的基本语法格式如下:

for(a:array){
   //循环体
}

//a是指数组中的元素,array是指要遍历的集合

方法三:toString

package Test;

import java.util.Arrays;

public class ArrayDemo {
    public static void main(String[] args) {
        int []array = {1,2,3,4,5};
        System.out.print(Arrays.toString(array));
    }
}

运行结果:

四.初始化值

五.案例

1.找出数组中的最大值

package Test;

public class ArrayMaxNumDemo {
    public static void main(String[] args) {
        int[] a = {1, 5, 9, 3, 4, 7, 6, 16, 34, 12, 3};
        //先假设数组的第一个值是最大值
        int max = a[0];
        //利用循环遍历,将假设的最大值与数组中的每一个值进行比较
        for (int i = 1; i < a.length; i++) {
            //若有比假设值更大,则替换;否则,不变
            if(max<a[i]){
                max=a[i];
            }else{
             
            }
        }
        System.out.println(max);
    }
}

2.找出数组中的第二大值

package Test;

public class ArrayMaxNumDemo {
    public static void main(String[] args) {
        int[] a = {1, 5, 9, 3, 4, 7, 6, 16, 34, 12, 3};
        int max = a[0];//最大值
        int sec = a[1];//第二大值

        if(sec > max){
            int i = max;
            max = sec;
            sec = i;
        }

        for (int i = 2; i < a.length; i++) {
            if(max<a[i]){
                sec = max;
                max=a[i];
            }else if(a[i] < sec){
                continue;
            }else{
                sec = a[i];
            }
        }
        System.out.println(sec);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值