简体   繁体   中英

How do I get a random string from this array to print as a winner?

This is the code so far, I am trying to get the last part of the script to print a random name from the array each time. However I am struggling to find a way to do this?

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);





    }

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

You're setting random immediately after creating the array. Java arrays are initially filled with the default value ( null , for all reference types, including String ), so you'll always choose the value null .

Put the random assignment somewhere after you assign values to the elements of name :

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

// Some other code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM