如何从此阵列中获取随机字符串以作为赢家打印?

时间:2017-10-25 00:04:57

标签: java arrays string random

这是到目前为止的代码,我试图让脚本的最后一部分每次都从数组中打印一个随机名称。但是我很难找到办法做到这一点?

import java.util.Arrays;
import java.util.Random;


public class ArrayTask2moredataseminar {

    public static void main(String[] args) {


        String[] name = new String[10];
        String random = (name[new Random().nextInt(name.length)]);


        name[0] = "Stewart";
        name[1] = "James";
        name[2] = "Duncan";
        name[3] = "John";
        name[4] = "Smith";
        name[5] = "Robertson";
        name[6] = "McGregor";
        name[7] = "Mayweather";
        name[8] = "Ian";
        name[9] = "Paul";

        //sorts arrays in java
        Arrays.sort(name);

        //searching on sorted array using binary search method
        if(Arrays.binarySearch(name, "Stewart") >=0) {
            System.out.println("The array contains " + name[0]);
        }

        if(Arrays.binarySearch(name, "Roach") >=0) {
            System.out.println("The array contains " + name[0]);
        }



        System.out.println(Arrays.toString(name));

        for (int i = 0; i < name.length; i++) {
            System.out.println(name[i]);

        }

        System.out.println("The Winner is: " + random);





    }

}

1 个答案:

答案 0 :(得分:2)

String[] name = new String[10];
String random = (name[new Random().nextInt(name.length)]);

您在创建阵列后立即设置random。 Java数组最初使用默认值null填充所有引用类型,包括String),因此您始终选择值null

在为random的元素指定值后,将name作业放到某处:

String[] name = new String[10];
name[0] = ...;
name[1] = ...; // etc

// Some other code.

random = name[new Random().nextInt(name.length)];