1.定义长度为5的整型数组,输入他们的值,用冒泡排序后输出.
1 public class homework 2 { 3 public static void main(String[] args) { 4 int[] arr = {3,5,9,7,1}; 5 for (int i = 0; i < arr.length; i++) { 6 for (int j = 0; j < arr.length-1-i; j++) { 7 int num = 0; 8 if(arr[j] > arr[j+1]){ 9 num = arr[j]; 10 arr[j]= arr[j+1]; 11 arr[j+1] = num; 12 } 13 } 14 } 15 for (int i : arr) { 16 System.out.println(i); 17 } 18 } 19 }
2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出"not found"
1 public class homework { 2 public static void main(String[] args) { 3 Scanner input=new Scanner(System.in); 4 boolean A=false; 5 int[] x=new int[]{34,22,35,67,45,66,12,33}; 6 System.out.print("请输入需要查找的数"); 7 int a=input.nextInt(); 8 for(int i=0;i<x.length;i++){ 9 if(x[i]==a){ 10 System.out.println("该数存在于数组中下标为"+i); 11 A=true; 12 } 13 } if(A==false){ 14 System.out.println("not found"); 15 } 16 } 17 }
3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。
1 public class homework 2 { 3 public static void main(String[] args) { 4 double arr[][] = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, 5 { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 } }; 6 for (int i = 0; i < arr.length; i++) { 7 for (int j = 0; j < arr[i].length; j++) { 8 System.out.print(arr[i][j] + " "); 9 } System.out.println(); 10 } 11 } 12 }
4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值
1 public class homework 2 { 3 public static void main(String[] args) 4 { 5 int arr[][]={{1,2,3},{4,5,6}, 6 {7,8,9},{10,11,12}}; 7 int max=arr[0][0]; 8 for(int i=0;i<arr.length;i++){ 9 for(int j=0;j<arr[i].length;j++){ 10 if(arr[i][j]>max){ 11 max=arr[i][j]; 12 } 13 } 14 } 15 System.out.println("数组的最大值为"+max); 16 } 17 }