定义长度为5的整型数组,输入它们的值,用冒泡排序输出
package dome6_2sixweek_sunday; import java.util.Scanner; public class a { public static void main(String[] args) { // TODO Auto-generated method stub int[] num = new int[5]; Scanner input = new Scanner(System.in); for (int i = 0; i < num.length; i++) { System.out.print("请输入第" + (i + 1) + "个数:"); num[i] = input.nextInt(); } for (int i = 0; i < num.length - 1; i++) { for (int j = 0; j < num.length - 1 - i; j++) { if (num[j] > num[j + 1]) { int temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; } } } for (int i = 0; i < num.length; i++) { System.out.print(num[i] + " "); } } }
定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在输出下标,不存在输出"not found"
package demo6_2sixweek_sunday; import java.util.Scanner; public class b { public static void main(String[] args) { // TODO Auto-generated method stub int i = 0; int a=0; int[] arr = { 34, 22, 35, 67, 45, 66, 12, 33 }; Scanner input = new Scanner(System.in); System.out.print("请输入一个数字:"); int n = input.nextInt(); for (int j = 0; j < arr.length; j++) { if (n == arr[j]){ i+=1; a=j;} else i+=2; } if(i%2!=0) System.out.println(a); else System.out.println("not found"); } }
用矩阵输出一个double型的二维数组(长度分别为5,4,值自己定)的值
package dome6_2sixweek_sunday; public class c { public static void main(String[] args) { // TODO Auto-generated method stub double[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 8, 7, 6 }, { 5, 4, 3, 2 }, { 1, 2, 3, 4 } }; for (int i = 0; i < arr.length; i++) { System.out.println(); for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } } } }
定义一个二维数组(长度分别为3,4,值自己定),求该二维数组的最大值
package dome6_2sixweek_sunday; public class d { public static void main(String[] args) { // TODO Auto-generated method stub int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 8, 7, 6 } }; int max = arr[0][0]; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (arr[i][j] > max) { max = arr[i][j]; } } } System.out.println("最大值为" + max); } }