第六周作业
1.定义长度位5的整型数组,输入他们的值,用冒泡排序后输出.
1 package pro1; 2 import java.util.*; 3 public class test { 4 public static void main(String[] args) { 5 int[] a = new int[5]; 6 int i, j; 7 int k; 8 Scanner input = new Scanner(System.in); 9 System.out.println("请输入5个整数:"); 10 for (i = 0; i < 5; i++) { 11 a[i] = input.nextInt(); 12 } 13 for (i = 0; i < a.length - 1; i++) { 14 for (j = 0; j < a.length - 1 - i; j++) { 15 if (a[j] > a[j + 1]) { 16 k = a[j]; 17 a[j] = a[j + 1]; 18 a[j + 1] = k; 19 } 20 } 21 } 22 System.out.println("冒泡排序:"); 23 for (i = 0; i < a.length; i++) { 24 System.out.println(a[i] + "\t"); 25 } 26 } 27 }
2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出"not found"
1 package pro1; 2 import java.util.*; 3 public class test { 4 public static void main(String[] args) { 5 Scanner a = new Scanner(System.in); 6 int[] b = { 34, 22, 35, 67, 45, 66, 12, 33 }; 7 int k = -1; 8 System.out.println("输入一个数"); 9 int c = a.nextInt(); 10 for (int i = 0; i < b.length; i++) { 11 if (b[i] == c) { 12 k = i; 13 System.out.println("下标为" + i); 14 break; 15 } 16 } 17 if (k == -1) { 18 System.out.println("not found"); 19 } 20 } 21 }
3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。
1 package pro1; 2 import java.util.*; 3 public class test { 4 public static void main(String[] args) { 5 double[][] a = {{1.1,2.2,3.2,4.4},{6.6,7.7,8.8,9.9},{12.1,13.5,14.5,15.5},{16.5,17.8,18,19.4},{11.2,12.2,13.3,14.4}}; 6 for(int i = 0;i < 5;i++) { 7 for(int k = 0;k < 4;k++) { 8 System.out.print(a[i][k]+" "); 9 } 10 System.out.println(); 11 } 12 } 13 }
4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值.
1 package pro1; 2 import java.util.*; 3 public class test { 4 public static void main(String[] args) { 5 double[][] a = {{1.1,2.2,3.2,4.4},{6.6,7.7,8.8,9.9},{12.1,13.5,14.5,15.5}}; 6 double max = a[0][0]; 7 for(int i=0;i<3;i++) { 8 for(int j=0;j<4;j++) { 9 if(max < a[i][j]) { 10 double b ; 11 b = max; 12 max = a[i][j]; 13 } 14 } 15 }System.out.println("最大值为:"+max); 16 } 17 }