Stew-coder95
Stew-coder95

Reputation: 39

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





    }

}

Upvotes: 0

Views: 55

Answers (1)

Andy Turner
Andy Turner

Reputation: 140564

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

Upvotes: 2

Related Questions