1.定义长度为5的整型数组,输入他们的值,用冒泡排序后输出.
(1)自定义数组:
import java.util.*; public class L { public static void main(String[] args) { int[] arr = {3,5,9,7,1}; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length-1-i; j++) { int num = 0; if(arr[j] > arr[j+1]){ num = arr[j]; arr[j]= arr[j+1]; arr[j+1] = num; } } } for (int i : arr) { System.out.println(i); } } }
(2)控制台输入数组:
import java.util.*; public class L { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("请输入数组的值:"); int[] arr= new int[5]; for(int i=0;i<arr.length;i++) { arr[i]=input.nextInt(); } for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length-1-i; j++) { if(arr[j] > arr[j+1]){ int temp=arr[j]; arr[j]= arr[j+1]; arr[j+1] = temp; } } } System.out.println("升序冒号排序为:"); for (int i=0;i<arr.length;i++) { System.out.println(arr[i]+" "); } } }
2.定义数组{34,22,35,67,45,66,12,33},输入一个数a,查找在数组中是否存在,如果存在,输出下标,不存在输出"not found"
import java.util.*; public class L { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean flag= false; int[]arr = {34,22,35,67,45,66,12,33}; System.out.println("请输入一个数:"); int a = input.nextInt(); for (int i = 0; i < arr.length; i++) { if (arr[i] == a){ System.out.println("该数在数组中存在它的下标是:" + i); flag = true; } } if(flag == false){ System.out.println("not found"); } } }
3.以矩阵的形式输出一个double型二维数组(长度分别为5、4,值自己设定)的值。
import java.util.*; public class L { public static void main(String[] args) { 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] + " "); } System.out.println(); } } }
4.定义一个二维数组(长度分别为3,4,值自己设定),求该二维数组的最大值.
import java.util.*; public class L { public static void main(String[] args) { int arr[][] = { {1,5,7,9},{6,8,9,7},{12,23,34,45}}; 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); } }