1.定义长度位5的整型数组,输入他们的值,用冒泡排序后输出.
package www; import java.util.Scanner; public class test{ public static void main(String[] args) { int[] arr= new int [5]; Scanner sc = new Scanner(System.in); System.out.println("依次输入数组中各元素的值"); for (int i = 0; i < arr.length; i++) { arr[i]=sc.nextInt(); } for (int i = 0; i < arr.length-1; i++) { for (int j = 0; i < arr.length-i-1; j++) { if(arr[j]>arr[j+1]){ int x=arr[j]; arr[j]=arr[j+1]; arr[j+1]=x; } } } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]+""); } } }
2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出"not found"。
package www; import java.util.Scanner; public class test{ public static void main(String[] args) { int[] arr= { 34, 22, 35, 67, 45, 66, 12, 33 }; Scanner sc = new Scanner(System.in); System.out.println("输入数字,查找它是否在数组中"); int x = sc.nextInt(); int y = 0; for (int i = 0; i < arr.length; i++) { if (x == arr[i]) { System.out.println("下标为:" + i); y=1; } } if (y == 0) { System.out.println("not found"); } } }
3..以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。
package www; import java.util.Scanner; public class test{ public static void main(String[] args) { double [][] arr={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20}}; for(int i=0;i<arr.length;i++){ for(int j=0;j<arr.length-1;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } } }
4..定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值。
import java.util.Scanner; public class test{ public static void main(String[] args) { int [][] arr={{20,31,51,5},{40,21,25,36},{52,36,92,41}}; int max=arr[0][0]; for(int i=0;i<arr.length;i++){ for(int j=0;j<arr.length+1;j++){ if(arr[i][j]>max){ max=arr[i][j]; } } } System.out.println("二维数组最大值为:"+max); } }