Now that we know how to use variables and add text, let’s combine the two. The skill of adding in variables when putting a message into a graphic or program is most helpful when working with math, if and if/else statements. But, it is also easier to learn the skill without all of the other parts that we will learn down the road.
What if you had a rectangle that had a height of 20 and a width of 50. You made a variable for each but you want to add it into a message. You could simply write text(“The rectangle’s width is 20 and the width is 50”, 90,90);. But what if you redefined it later or changed the variable?
Adding in variables to your text is easy and will save you the time of editing the text code later. The variable cannot be in the quotation marks, though. If they are, the computer won’t know to add in the variable’s value and will just put the name in.
A text code that has a variable will look like this: text(“message ” + variable, x-coordinate, y-coordinate);. If you wanted to wrap the variable with text it would look like this: text(“message ” + variable + “message”, x, y);. You can add as many variables in a message as you want as long as they aren’t in the quotation marks. Any part of your message that isn’t a variable is in quotation marks, though.
Leave a space in your message before the variable and after the variable. If you don’t everything will run together. Write the message as if the variable isn’t there when typing. You code should look like this:
Play around with adding variables into your message. They can go in any order so don’t be afraid to mix things up!