Java 学习(08)--数组常见问题

1.数组遍历(依次输出数组中的每一个元素)

//数组遍历(依次输出数组中的每一个元素)public class shuzu1{	public static void main(String[] args){		int[] a = {1,2,3,4,5,6,7,8,9};		for(int i = 0;i < a.length;i++){			System.out.println(a[i]);		}	}}

运行:

2.//数组获取最值(获取数组中的最大值最小值)

//数组获取最值(获取数组中的最大值最小值)public class shuzu2{	public static void main(String[] args){		int[] a ={1,2,3,4,5,6};		//获取数组中的最大值		int max = a[0];		for(int i = 0;i < a.length;i++){			if(a[i] > max){				max = a[i];			}		}		System.out.println("数组中的最大值:"+max);				//获取数组中的最小值		int min = a[0];		for(int i = 0;i < a.length;i++){			if(a[i] < min){				min = a[i];			}		}		System.out.println("数组中的最小值:"+min);	}}

运行

3.数组元素逆序 (就是把元素对调)

//数组元素逆序 (就是把元素对调)public class shuzu3{	public static void main(String[] args){		int[] a ={10,2,30,4,50,6};		int[] b =new int[a.length];		for(int i = 0;i < a.length;i++){			b[i] =a[a.length-1-i]; 		}		for(int i = 0;i < b.length;i++){			System.out.println(b[i]);		}	}}

运行:

方法二:

//数组元素逆序 (就是把元素对调)public class shuzu3{	public static void main(String[] args){		int[] a ={10,2,30,4,50,6};		for(int i =0;i < a.length/2;i++ ){			int temp = a[i];			a[i] = a[a.length-1-i];			a[a.length-1-i] = temp;		}		for(int i = 0;i < a.length;i++){		System.out.println(a[i]);		}	}	}

运行:

4.数组查表法(根据键盘录入索引,查找对应星期)

//数组元素查找(查找指定元素第一次在数组中出现的索引import java.util.Scanner;public class homework4{	public static void main(String[] args){		Scanner s = new Scanner(System.in);		System.out.println("请输入你要查找的数据");		int num = s.nextInt();				int[] a = {0,1,2,3,4,5,6,7,8,9};		for(int i = 1;i < a.length;i++){			if(num == a[i]){				System.out.println("第一次在数组中出现的检索为:"+i);				break;			}		}	}}

运行:

5.数组元素查找(查找指定元素第一次在数组中出现的索引)

收藏 打印