1.定义长度位5的整型数组,输入他们的值,用冒泡排序后输出.
Scanner sc = new Scanner(System.in); int[] arr = new int[5]; for (int i = 0; i < arr.length; i++) { System.out.print("请输入第" + (i + 1) + "个值:"); arr[i] = sc.nextInt(); } for (int x = 0; x < arr.length - 1; x++) { for (int y = 0; y < arr.length - x - 1; y++) { if (arr[y] > arr[y + 1]) { int temp = arr[y]; arr[y] = arr[y + 1]; arr[y + 1] = temp; } } } for (int n : arr) { System.out.println(n + ", "); }
2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出"not found"
Scanner sc = new Scanner(System.in); System.out.print("请输入一个数:"); int a = sc.nextInt(); boolean choice = false; int arr[] = { 34, 22, 35, 67, 45, 66, 12, 33 }; for (int i = 0; i < arr.length; i++) { if (a == arr[i]) { System.out.println("该数的的下标为:" + i); choice = true; } } if (choice == false) System.out.println("NOT FOUND!");
3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。
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[i].length; j++) { System.out.print(arr[i][j] + "/t"); } System.out.println(); }
4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值.
Scanner sc=new Scanner(System.in); System.out.print("请输入二维数组行数:"); int row=sc.nextInt(); System.out.print("请输入二维数组列数:"); int col=sc.nextInt(); int [][] arr=new int[row][col]; System.out.println("请输入二维数组中的元素(以空格为间隔):"); for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) { arr[i][j]=sc.nextInt(); } System.out.println(); } int max=0; for(int x=0;x<arr.length;x++) { for(int y=0;y<arr[x].length;y++) { if(max<arr[x][y]) { max=arr[x][y]; } } } System.out.println("该数组中最大值为:"+max);