I. Tutorial Purpose
1. Understand the declaration, creation, initialization, and use of arrays in Java.
2. Understand the common methods for sorting arrays in Java.
3. Learn how to find a specific value in an array.
Ii. experiment content
This program will randomly generate 10 numbers (20-80) into the array, find the maximum number and its subscript.
Public class Array {public static void main (String agrs []) {int a [] = new int [10]; int I; for (I = 0; I <10; I ++) {a [I] = (int) (Math. random () * (50-20) + 20; System. out. print (a [I] + "");} System. out. println (); int max; int row; max = a [0]; row = 0; for (I = 1; I <10; I ++) {if (max
Running result
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink">
VcD4KPHA + PGJyPgo8L3A + CjxwPjxwcmUgY2xhc3M9 "brush: java;">/*** use a random function to generate a 4 × 4 matrix (two-dimensional matrix) with an integer in the range of [20, 50, calculate the sum of the elements on the two diagonal lines. **/Public class exam7 {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubint sum = 0; int array [] [] = new int [4] [4]; for (int I = 0; I <4; I ++) {for (int j = 0; j <4; j ++) {array [I] [j] = (int) (Math. random () * (50-20) + 20); if (j % 4 = 0) System. out. println (); System. out. print ("" + array [I] [j]); if (I = j | I + j = 3) sum + = array [I] [j] ;}} System. out. println (); System. out. println ("sum of elements on the two diagonal lines: sum =" + sum );}}
Running result
// The output format is incorrect. It needs to be improved...
Package packagesevth;/** create and output a 10*10 matrix. The diagonal element of this matrix is 1, and the remaining elements are 0. Output this array. **/Public class array007 {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubint array [] [] = new int [10] [10]; for (int I = 0; I <10; I ++) {for (int j = 0; j <10; j ++) {if (I = j | I + j = 9) array [I] [j] = 1; elsearray [I] [j] = 0; if (j = 9) System. out. println (); System. out. print ("" + array [I] [j]) ;}}}
Running result
Package packageeight;/** the program will randomly generate 10 numbers (20-80) into the array, output the array, and then sort the array in ascending order, and output the sorted array. **/Public class arraysort {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stubint array [] = new int [10]; int temp = 0; System. out. println ("array before sorting:"); for (int I = 0; I <10; I ++) {array [I] = (int) (Math. random () * (80-20) + 20); System. out. print ("" + array [I]);} System. out. println (); System. out. println ("sorted array:"); for (int I = 0; I <10; I ++) {for (int j = 0; j <10-i-1; j ++) {if (array [I]> array [I + 1]) {temp = array [I]; array [I] = array [I + 1]; array [I + 1] = temp;} System. out. print ("" + array [I]) ;}}
Running result