开发者

how do i link an int to a string inside a string array java

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


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


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜