1.定义长度为5的整型数组,输入他们的值,用冒泡排序后输出。
import java.util.Scanner; public class C { public static void main(String[] args) { // TODO Auto-generated method stub int [] a=new int[5]; Scanner sc=new Scanner(System.in); for(int i=0;i<5;i++) { System.out.println("输入第"+(i+1)+"个数:"); int n=sc.nextInt(); a[i]=n; } for(int i=0;i<=a.length-1;i++) { for(int j=0;j<a.length-i-1;j++) { if(a[j]>a[j+1]) { int max; max=a[j]; a[j]=a[j+1]; a[j+1]=max; } } } for(int b:a) { System.out.println(b); } } }
2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出
"not found"
import java.util.Scanner; public class C { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); boolean flag= false; int[] a = {34,22,35,67,45,66,12,33}; System.out.println("输入一个数:"); int b = input.nextInt(); for (int i = 0; i < a.length; i++) { if (a[i] == b) { System.out.println("该数的下标是:" + i); flag = true; } } if(flag == false){ System.out.println("not found"); } } }
3.以矩阵的形式输出一个
double
型二维数组(长度分别为5、4,值自己设定)的值。
import java.util.Scanner; public class C { public static void main(String[] args) { // TODO Auto-generated method stub double[][] arr = { { 2.3,6.5,7.8,9}, { 5.5,2.9,8.4,5.6 }, { 41.8,28.6,66,53 }, { 11.6,24.8,2.9,3 }, { 56,22.3,50.4,25.6 } }; System.out.println("矩阵形式输出"); for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - 1; j++) { System.out.print(arr[i][j] + " "); } System.out.println(" "); } } }
4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值.
import java.util.Scanner; public class C { public static void main(String[] args) { // TODO Auto-generated method stub double[][] a = new double[][]{{1,2,3}, {6,7,8}, {11,12,13}, {16,17,18}}; double max = 0; for (double[] i : a) { for (double j : i) { if (j > max) { max = j; } } } System.out.println("最大值为" + max); } }