Lesson 3: Variables, Part 2 Concatenation and Random Numbers Concatenation Often, you will want to combine Strings and other types of variables to make a new String. As with Visual Basic, you do this with concatenation. In VB, you used an ampersand (remember? Msgbox(“Gold: “ & x) ). In java, use a plus: public class ConcatenationExample { public static void main (String [] args) { int i = 6; System.out.println(i + “ is a small number”); } } When you use the plus operator with a String and a non-String (or another String), the result is a combined String. Random Numbers: To get a random double in java with a value from 0 to slightly less than one, use Math.random() as shown below. Note that what you get is essentially a percentage, such as .37164 (about 37%). public class RandomExample1 { public static void main (String [] args) { double percent = Math.random(); System.out.println(“Your random number is: “ } + percent); } To get a random integer in java with a value from lower to upper, inclusive, use this formula: (int) ((upper – lower + 1) * Math.random() + lower) 1|©Joshua Britton For example: public class RandomExample2 { public static void main (String [] args) { int upper = 11; int lower = 3; //result is 3 to 11, inclusive int result = (int) ((upper - lower + 1) * Math.random() + lower); System.out.println(result); } } ASSIGNMENT ConcatenateRandom description: Use Notepad to create a file named “ConcatenateRandom.java”. Make sure you use quotation marks to force Notepad to avoid appending “.txt”. Write a program using the same structure as all the examples in this packet. The first line must state public class ConcatenateRandom { Place all the code in the main method (just like in the examples in the packet). 1. Generate a random percentile, store it in a variable, and display the variable using concatenation (see example output, below). 2. Generate an integer from 3 to 9 (inclusive) store it in a variable and display the variable using concatenation (see example output, below). 3. Generate a decimal from 0 to .2, store it in a variable and display the variable. 4. Add the variables from steps 1, 2 and 3 and store the results in a fourth variable. Display the problem as a sum and a result (see example output, below). Example Output Random Random Random .79031 Percentile: .79031 Integer: 8 Decimal from 0 to .2: .0039 + 8 + .0039 = 8.79421 SUBMISSION: Put your name at the top of the code, then print it and give it to me 2|©Joshua Britton