• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

实验4.3 二维数组

编写一个Java程序,定义一个2行3列的整型二维数组,对数组中的每个元素赋一个1~100的随机整数值,然后分别对第一行、第二行的元素进行排序,使程序运行结果如下。

 

Math类的random()方法返回[0.0,1.0)的随机数,而想要得到A~B得随机整数的代码应为(int)Math.random()*(B-A+1)+A,因为random()是静态方法,所以可直接用类名Math调用。

对数组排序的方法有很多种,这里用到了数组类Arrays中的sort的方法。该类在java.util包中。

package com;
import java.util.Arrays;
public class sentence {
    public static void main(String[] args)
    {
        int i,j;
        int a[][];
        a=new int[2][3];
        for(i=0;i<2;i++)
        {
            for(j=0;j<3;j++) {
                a[i][j] = (int) (Math.random() * 100) + 1;
                System.out.print("a[" +i+ "]" + "[" +j+ "]=" + a[i][j] + " ");
            }
            System.out.println();
        }
        Arrays.sort(a[0]);
        Arrays.sort(a[1]);
        for(i=0;i<2;i++)
        {
            if(i==0)System.out.print("排序后,第一行元素从小到大是:");
            else System.out.print("排序后,第二行元素从小到大是:");
            for(j=0;j<3;j++)
                System.out.print("a["+i+"]"+"["+j+"]="+a[i][j]+" ");
            System.out.println();
        }
    }
}

Arrays.sort(int[ ] a)

这种形式是对一个数组的所有元素进行排序,并且是按从小到大的顺序。

Arrays.sort(a);

Arrays.sort(int[] a, int fromIndex, int toIndex)

这种形式是对数组部分排序,也就是对数组a的下标从fromIndex到toIndex-1的元素排序,注意:下标为toIndex的元素不参与排序。

 Arrays.sort(a, 0, 3);

例如:1 7 6 8 6 8

输出:1 6 7

posted on 2022-04-12 20:02  王陈锋  阅读(53)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3