JAVA基础(23)---数组的常用操作

版权声明:如需转载请标明出处 https://blog.csdn.net/yj201711/article/details/83749316

数组的一些常用操作

数组元素的遍历

① 正序  ② 逆序

public class ArryDemo{

    public static void main(String[] args){

        int[] arry = {2,5,3,7,6}
        //正序遍历数组
        for(int i = 0 ; i < arry.length ; i++){
        
            System.out.println(arr[i]);

        }

         //逆序遍历
         for(int i = arry.length-1 ; i > -1 ; i--){
        
            System.out.println(arr[i]);

        }
    }
}

查找数组中的元素

查找指定元素第一次在数组中出现的索引,如果有,则返回元素在数组中的索引;如果没有找到,则返回-1

public class ArrayDemo4{
	public static void main(String[] args){
			int[] arrays = {2,1,6,4,6,9};
			int index = findElement(arrays,6);
			System.out.println(index);
	
	}
	//查找元素
	public static int findElement(int[] arr,int key){
		
		for(int i = 0 ; i < arr.length ; i++){
			if(arr[i] == key){
				return i;	
			}
		}
		return -1;
	
	}
}

如果是查找最后一次出现的位置,逆序遍历数组即可。

查找数组中的最大值和最小值

public class ArrayDemo3{

	public static void main(String[] args){
		int[] arr = {2,3,5,7,9}; 

		//查找数组中的最大值或者最小值
		
		int max = 0 ;
		for(int i = 0 ; i < arr.length;i++){
			if(arr[i] > max){
				max = arr[i];
			}
		}
		System.out.println(max);
}
}

猜你喜欢

转载自blog.csdn.net/yj201711/article/details/83749316