java:随机数学习Random,str.charAt(index)字符串索引,字符串函数

1java:random都有那些API,字符串位置:

nextInt(参数);
返回一个随机、均匀分布的 int值在0~参数。

字符串:
str.charAt(index); //返回一个字符
对str:进行索引。索引位置为index的字符。从
如:str=“apple” ,那么 index=0, 就是 str位置的 a。

例子:
随机返回一个数,随机返回一个字符

package com.example.demo17;

import java.util.Random;

public class erzdwf {


    public static void main(String[] args)

    {

        Random random=new Random();

       System.out.println(random);//java.util.Random@63947c6b

System.out.println(random.nextInt(10)); //随机生成0~10,整数


        String str="abcdeflmiABCDJEKFFLK123456789QWERRGUGWJFQ";

        Random sc=new Random();
       // StringBuffer qqq=new StringBuffer();

        int number=random.nextInt(30);//生成0~30数字


       // qqq.append(str.charAt(number));
       System.out.println(str.charAt(number)); //随机数不能大于字符串长度,否则报错

    }



}

效果:
在这里插入图片描述

2.例子2:随机返回字符串4位数:

StringBuffer bc=new StringBuffer(); //可以改变的字符串,可以增加字符,
bc.append(app);//按顺序增加字符

  String str="abcdeflmiABCDJEKFFLK123456789QWERRGUGWJFQ";
  StringBuffer bc=new StringBuffer();  //bc是可以变化的字符串,变量

        for(int i=0;i<4;i++){
            int qqq=random.nextInt(30);
           char app= str.charAt(qqq);

bc.append(app);


        }

        System.out.println(bc);

效果:
在这里插入图片描述

3.例子3:

package com.example.demo17;

import java.util.Random;

public class erjtkg {




    public static void main(String[] args){

        StringBuffer bx=new StringBuffer();

        Random random=new Random();


        String st1="1234567890";
        String st2="abcdefghtlmnopqrstuvwsyz";
        String st3="ABCDEFQOODJFRMGUIPWRK";
        String st4="!@#$%^&*()";

       bx.append( st1.charAt(random.nextInt(10)));
        bx.append( st2.charAt(random.nextInt(24)));
        bx.append( st3.charAt(random.nextInt(20)));
        bx.append( st4.charAt(random.nextInt(5)));

        System.out.println(bx);




    }





}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半浮名

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值