1.定义长度位5的整型数组,输入他们的值,用冒泡排序后输出
public class test1 { public static void main(String[] args) { int a[]=new int[5]; Scanner x=new Scanner(System.in); System.out.print("请输入5个数"); for(int i=0;i<5;i++)//for循环控制输入五整型数 a[i]=x.nextInt(); int t; //冒泡排序 for(int i=0;i<4;i++)//总共需要5-1次外循环 for(int j=0;j<4-i;j++)// if(a[j]>a[j+1]){//相邻两个数比较,如果前一个数较大,则交换位置 t=a[j]; a[j]=a[j+1]; a[j+1]=t; } System.out.println("从小到大输出:"); for(int i=0;i<5;i++) System.out.print(a[i]+" "); } }
2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出"not found"
package chap; import java.util.Scanner; public class test1 { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean flag= false; int[] b = {34,22,35,67,45,66,12,33}; System.out.println("请输入一个数:"); int a = input.nextInt(); for (int i = 0; i < b.length; i++) { if (b[i] == a) { System.out.println("该数的下标是:" + i); flag = true; } } if(flag == false){ System.out.println("not found"); } } }
3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值
package chap; public class test1{ public static void main(String[] args) { // TODO Auto-generated method stub double[][] arr = { { 3.6,5.5,5.3,9.4 }, { 9.1, 15,2, 1.3, 9.6 }, { 7.1, 9.2, 1.3,3.4 }, { 5.1, 7.2,7.6,31.4 }, { 7, 35,97, 35} }; 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,值自己设定),求该二维数组的最大值.
package chap; import java.util.*; public class test1{ public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("请输入数组的值:"); int [][] arr=new int[3][4]; for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) { arr[i][j]=input.nextInt(); } } int max=0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { if (max < arr[i][j]) { max = arr[i][j]; } } } System.out.println("最大值为" + max ); } }