• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to display desired message?  RSS feed

 
Chris Whitcomb
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the below code inside a method and what I’m trying to do is, if the user gets the answer right, display one of the 3 messages below. However, I want the computer to randomly pick which message so I created an instance variable:
Random generator = new Random(). I’m trying to take that random number of between 1 and 3 and attach it to the word “message” and then display either message1, message2, or message3 in a Text field. However, when I run the below code what appears in the Text Field is the actual words “message1”, “message2”, or “message3” and not the variable those name represent.


                 String message1 = "Very Good!";
                 String message2 = "Excellent!";
                 String message3 = "Great job!";
                
                 String displayMessage = "message" + String.valueOf(1 + generator.nextInt(3));
                
                 // Randomly pick one of the messages to display
                 responseJTextField.setText(displayMessage);
 
Carey Brown
Saloon Keeper
Posts: 3310
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First off, you'll need an array of messages

Then create a Random object

Then use rand to get random message
 
Junilu Lacar
Sheriff
Posts: 11476
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

Have you learned about arrays yet?  Arrays are data structures that hold things that you can reference by numeric indices. In Java, array indices start at 0 for the first element of the array, 1 for the second element, and so on.

For example, if you declare an array of integers likes this:

Then you write this:

you'll get this output:

numbers[0] is 5
numbers[1] is 4
numbers[2] is 11

You'll need to do something similar in your code, except you'll use the number that Random.nextInt() gives you as the index to the array of messages you want to display. Note that you'll need an array of String objects in your code, not an array of int values like I have in my example above.

See the Java Tutorial on Arrays for more examples.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!