• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
百事可爱
一起努力鸭~~~
博客园    首页    新随笔    联系   管理    订阅  订阅
java 初学Arrays类 Random类

学习Arrays类

学习Arrays类,在java.util.Arrays的包下,需要引入import java.util.Arrays;sort()对指定数组进行排序

import java.util.Arrays;
public class student {

	public static void main(String[] args) {
	int a[]={3,4,5,7,0 };
	Arrays.sort(a);//数组名
	System.out.print("排序后:");
	for(int i=0;i<a.length;i++)
	{
		System.out.print(a[i]+",");
	}
		
	}

}
 import java.util.Arrays;
import java.util.Scanner;
//binarySearch() 对排序数组进行二分搜索,找到则返回该值的索引,否则返回负值
//搜索前要求数组是先排好序的
public class stu {
	public static void main(String[] args) {
		int a[]={3,4,5,7,0 };
		Arrays.sort(a);// 先升序排好数组
		System.out.print( "请输入搜索值:");
		Scanner b = new Scanner(System.in);
		int k=b.nextInt();//输入要在数组中搜索的值
		int f=-1;//设标记位f
		if((f=Arrays.binarySearch(a,k))>-1){//binarySearch()中需要两个参数,要搜索的数组,和要搜的数
			System.out.print("找到值的索引"+f+"的位置");
		}
		else{
			System.out.println("找不到指定值");
		}
		

	}

  import java.util.Arrays;
//equals()方法,比较两个数组中的元素值是否全部相等
public class stu2 {

	public static void main(String[] args) {
		 
		int a[]={3,4,5,7,0 };
		int b[]={3,4,5,7,0 };
/*对比比较运算符"==",数组属于引用数据类型,引用存储数组对象的首地址,要比较两个数组是否相等,就是数组的
 * 引用,即首地址是否相同,是就返回 true
 * */
		System.out.println(a==b);
		System.out.println(Arrays.equals(a,b));
	}

}

学习Random类

//Random类,在java.util.Random包里

//nextDouble()生成一个随机的double值,范围是[0,1.0)
//nextInt()生成一个随机的int值
//nextInt(int n)生成一个随机的int值,范围[0,n)
import java.util.Random;
public class r1 {
public static void main(String[] args) {
Random r=new Random();//构造Random类对象
int a=r.nextInt();//任意的随机整数
int b=r.nextInt(10);//0~9的任意整数****
double c=r.nextDouble();//任意浮点数0~1.0
System.out.println(a);
System.out.println(b);
System.out.println(c);
//因为随机,则每次输出不同

}

}

实例应用

import java.util.Arrays;

import java.util.Random;

//要求随机产生并按升序输出1~30之间的7个数,任意两个数不能重复
//用Random类产生随机数,使用数组存储,不能重复,排序并输出
public class stu3 {

public static void main(String[] args) {
	 Random r=new Random();
	 int a[]=new int[7];
	 for(int i=0;i<a.length;i++){//产生随机数放入数组中
		 a[i]=r.nextInt(30)+1;//因为Random中nextInt(30)产生0~29的随机数,所以在此基础上加1
		 for(int j=0;j<i;j++)
		 {
			 if(a[i]==a[j]){//判断重复
				 i--;//利用brreak 退出循环,使在i处重新再分配一个新的随机数
				 break;
			 }
		 }
		 
	 }
	 Arrays.sort(a);
	 for(int i=0;i<a.length;i++){
		 System.out.print(a[i]+" ");
	 }

}

}

posted on 2021-09-30 15:22  精致猪猪侠  阅读(97)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3