【程序28】题目:对10个数进行排序
public class Demo1 {
public static void main(String[] args) {
int a[] = new int[10];
Random r=new Random();
for(int i=0;i<10;i++){
a[i]=r.nextInt(100)+1;//得到10个100以内的整数
System.out.print(a[i]+" ");
}
System.out.println();
for(int i =0;i<a.length-1;i++){
for(int j =0;j<a.length-1-i;j++){
if(a[j]>a[j+1]){
int temp =a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(int i=0;i<10;i++){
System.out.print(a[i]+" ");
}
}
}
【运行结果】
99 14 31 89 68 99 43 21 76 51
14 21 31 43 51 68 76 89 99 99
【程序29】题目:求一个3*3矩阵对角线元素之和
public class Demo1 {
public static void main(String[] args) {
double sum = 0;
int array[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 7, 8 } };
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
if (i == j)
sum = sum + array[i][j];
}
System.out.println(sum);
}
}
【运行结果】
14.0
【程序30】题目:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
import java.util.Random;
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int a[] = new int[11];
Random r=new Random();
for(int i=0;i<10;i++){
a[i]=r.nextInt(100)+1;//得到10个100以内的整数
}
for(int i =0;i<10-1;i++){
for(int j =0;j<10-1-i;j++){
if(a[j]>a[j+1]){
int temp =a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.print("插入前序列:");
for(int i=0;i<10;i++){
System.out.print(a[i]+" ");
}
System.out.println();
int flagI=0;
for(int i=0;i<a.length;i++){
if(n<a[i]){
flagI=i;
break;
}
}
for(int i=a.length-1;i>flagI;i--){
a[i]=a[i-1];
}
a[flagI]=n;
System.out.print("插入后序列:");
for(int i=0;i<11;i++){
System.out.print(a[i]+" ");
}
}
}
【运行结果】
12
插入前序列:8 29 32 36 41 55 62 72 74 88
插入后序列:8 12 29 32 36 41 55 62 72 74 88