0

Im relatively new to Java and cant seem to get a straight answer from my lecturer at college, so I apologise if this is a dumb question. I'm creating a level up screen for my assignment, and it needs to include an array.

I've created a string array called "randomTitle" containing a list of character titles, I need a button to pull a random title from my array list and display it on a JLabel on my level up screen, but am unsure how to save the random title returned as a variable in order to display it, can anyone help me?

Random ran = new Random();
String ary = randomTitle[ran.nextInt(randomTitle.length)];
titleJLabel.setText(String.valueOf(randomTitle));
1
  • 5
    "but am unsure how to save the random title returned as a variable" ... ask yourself what variable ary is, then you might know it. Commented May 18, 2016 at 21:32

3 Answers 3

1
Random rand = new Random();
int random = (int) (Math.random()*randomTitle.length);
titleJLabel.setText(randomTitle[random]);

So through a slow process of elimination, this ended up solving my issue, I tried setting the JLabel to ary to begin with, which displayed my entire array, useful to know but not what I was aiming for. I've tested the programme over and over now and it seems to be working perfectly fine, Thanks a lot guys!

Sign up to request clarification or add additional context in comments.

Comments

0

From what I can tell, you're trying to set the JLabel to a random address in the string array randomTitle. You already have the answer, if that's your question. However, for some reason you seem to be setting the JLabel to String.valueOf(randomTitle). What you want to be doing is setting the JLabel to the random address, which you already have stored in ary. Try setting the JLabel to ary.

Good luck!

Comments

0

Here it is as a one-liner using nextInt

titleJLabel.setText(randomTitle[Math.random().nextInt(randomTitle.length)]);

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.