1

im writing a program where I have to have the computer randomly choose 1 of 10 objects that i have written down as a string array... im using the the math.random function to come up with a number...

int targetNumber = (int) (Math.random() * 10);
System.out.println("I'm thinking of an item, I will only choose one of 10...");

how do i link that randomly generated int to a string inside a string array with ten different items inside... first time doing java and a pretty big noob, keep failing at this part

public static String getElement(int x){ 

    String[] stringArray = new String[10];

        stringArray[0] = "Gold";
        stringArray[1] = "Barnacle";
        stringArray[2] = "Wenches";
        stringArray[3] = "Wooden Leg";
        stringArray[4] = "Davey Jones Locker";
        stringArray[5] = "Keira Knightley";
        stringArray[6] = "Capt. Sparrow's Sword";
        stringArray[7] = "The Black Pearl";
        stringArray[8] = "Davey Jones Heart";
        stringArray[9] = "Diamonds";

    return stringArray[x];
}

its pirates of the caribean themed... school work

1
  • Could you edit your question to clarify what you mean when you say "link that randomly generated int to a string inside a string array with ten different items inside"? Commented May 26, 2011 at 23:51

3 Answers 3

3

With the code you posted, you can just do:

int targetNumber = (int) (Math.random() * 10);
System.out.println("I'm thinking of an item, I will only choose one of 10...");
System.out.println(getElement(targetNumber));
Sign up to request clarification or add additional context in comments.

Comments

1

You want to select one of the Strings. This is done by addressing the String array's index. Target number will generate that index, so what you do is stringArray[targetNumber]. This will return the String at the designated index.

If targetNumber is 3, "Wooden leg" will be selected.

Try it with System.out.println(getElement(targetNumber));

Hope that helps.

Comments

0

You can use stringArray[targetNumber] to get the string "pointed to" by the random number.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.