数组和矩阵及应用(java)

这篇博客旨在介绍Java中数组的使用,包括声明、创建、初始化,并探讨了如何对数组进行排序和查找特定值的方法。实验内容是通过生成10个20-50之间的随机数,存入数组并找出最大值及其对应的下标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



一、实验目的

1.掌握Java中数组的声明、创建、初始化和使用。

2.了解Java中提供的对数组排序的常用方法。

3.了解在数组中查找一个特定的值的常用方法。

二、实验内容



该程序将随机生成的10个数(20-50)放入数组中,找出其中最大数及其下标。

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=0;i<10;i++)
       {
         if(max<a[i])
         {
           max=a[i];
           row=i;
         }
       }
       System.out.println("最大值为"+max);

       System.out.println("最大值位置为"+row);
    } 
}

运行结果如图:






/*
 * 利用随机函数生成一个4×4的矩阵(即二维矩阵),范围是[20,50]内的整数,求它的两条对角线上元素之和。
 * 
 */
public class exam7 {


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int 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="+sum);
			
	}


}

运行结果如图:








//输出格式不对,待完善...

package packagesevth;
/*
 * 建立并输出一个10*10的矩阵,该矩阵对角线元素为1,其余元素均为0。输出该数组。
 * 
 */

public class array007 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int 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;
				else
					array[i][j] = 0;
				
				if (j==9)
					System.out.println();
				System.out.print("  "+array[i][j]);
			}
			
		}
	}

}



运行结果如图:






package packageeight;
/*
 * 程序将随机生成的10个数(20-80)放入数组中,输出该数组,再将数组按从小到大排序,并输出排序后的数组。
 * 
 */
public class arraysort {


	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int array[] = new int [10];
		int temp = 0;
		System.out.println(" 排序前数组:");
		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(" 排序后数组:");
		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]);
		}
		
	}


}


运行结果如图:











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值