mardi 24 octobre 2017

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





}

}




Aucun commentaire:

Enregistrer un commentaire