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

浙公网安备 33010602011771号