有没有会的给个注释!数组的!!

问题描述:

定义string类型数组 添加几个人名 随机抽取一个 用返回值 调用显示结果


import java.util.Random;

public class Test2 {
    public static void main(String[] args) {
        String name = Test2.method();//调用方法获取随机获取的名字的结果
        System.out.println(name);
    }
    public static String method(){
        //定义数组
        String[] strs = {"张三","李四","王五","赵六"};
//创建Random对象,用来获取随机数
        Random r = new Random();
//定义变量接收0-3的随机数
        int i = r.nextInt(4);
//利用随机数当做数组的索引,因为索引是随机的,所以s1也是随机的
        String s = strs[i];
        //返回随机抽取的结果
        return s;
    }
}

设置一个随机数,范围0到多少个人数,再定义这个随机数,之后就是输出str[i]

package com.offcn.third;

import java.util.Random;

public class Demo03 {
public static void main(String[] args) {
//定义数组
String[] s = {"张三","李四","王五","赵六"};
//创建Random对象,用来获取随机数
Random r = new Random();
//定义变量接收0-3的随机数
int i = r.nextInt(4);
//利用随机数当做数组的索引,因为索引是随机的,所以s1也是随机的
String s1 = s[i];
}
}