Math.random( )

Though not officially part of the curriculum, we will often want a quick way to populate an array with numbers. The Math class that comes with Java offers many static "class" functions that can be accessed directly from Math. So you just type:

Math.

and then from the list of functions that pops up, you choose:

Math.random( )

The random function returns a double of some random value between 0 and 1. (In fact, 0 is possible, but 1 is not, so the highest value possible is actually 0.99999999999.) Consider this often useful example:

if(Math.random() < 0.5){ System.out.println("50 % of the time the number will be below 0.5"); }else{ System.out.println("And 50% of the time, above 0.5"); }

Adjusting the Math.random( ) Returned Range

Most often we will want a random value within some other range than 0 to 1, so we can factor and shift the result by multiplying and/or adding to the originally returned value.

**Multiplying** gives us the **absolute range** of values.

Consider the following example:

System.out.println(Math.random() * 100);

The lowest possible value returned by Math.random( ) is 0, so the lowest possible outcome of the above expression is 0 * 100, or 0.

And the highest possible value returned by Math.random( ) is (almost) 1, so the highest possible outcome of the above example is 1 * 100, so (almost) 100.

The range of possible values is therefore 0 - 100. We might get 55, or 72, or 3, or 99, or any number between 0 and 100.

**Adding** (or subtracting) gives us the **shifted range** of values.

Consider the following example:

System.out.println(Math.random() * 100 + 20);

The lowest possible value returned by Math.random( ) is 0, so the lowest possible outcome of the above expression is 0 * 100 + 20, or 20.

And the highest possible value returned by Math.random( ) is (almost) 1, so the highest possible outcome of the above example is 1 * 100 + 20, so (almost) 120.

The range of possible values is therefore 20 - 120. We might get 55, or 20, or 113, or 119, or any number between 22 and 100.

(If it had been * 100 - 20, the range would be -20 to 80.)

Often we will want to change the data type of a variable from one data type to another, like from double to int, or from short to String.

In fact, the notes above points to one such situation. Math.random( ) returns a double, with lots of decimal places. So if you just went Math.random( ) * 100 + 20, you wouldn't actually get, say, 42, you'd get, say, 42.809834637103904. And such precision may not be either necessary or convenient for you in your given situation. So you'd want to convert the double to an int, or put another way "cast" the int to a double. Casting is to change a variable (or constant) from one data type to another.

To get the 42 you wanted in the above example, you'd go:

System.out.println((int) (Math.random() * 100 + 20));

The technique is to put, in parentheses, the data type you want to cast to, in front of the expression you want to convert. Often times that expression will be a compound expression, so you have to surround it in parentheses also - as was the case in the example above.

Here are a couple more examples of casting.

(int) ('A') - yeilds 65

(short) (3.9) - yelids 3

(String) (42) - yields 42

Notes on Casting

Note that casting happens implicitly when combining two data types. When you "add" two variables (or constants) of different data types, the one which is the smaller data type becomes casted to the larger data type.

Consider:

System.out.println('A' + "hello");

The result is the String Ahello, since String is a larger data type than char.

System.out.println(33 + "hello");

Same thing, the result is the String 33hello, since String is a larger data type than int.

System.out.println(33 + "66");

The result is 3366, because String is a larger data type than int.

**Casting to String**

And note that often a method will require a String as a parameter, but we give it some other kind of data. (This happens a lot when we get into "GUI" environments, with buttons and scroll bars etc.) The solution is simply to add an empty String "" to the expression, which implicitly casts it to String. For example:

myJTextField.setText(42 + "");

13 14 15 boolean moreTeamsToAdd = true; 16 while(moreTeamsToAdd){ 17 System.out.println("What is the name of the team?"); 18 String name = snr.nextLine(); 19 sportsTeams.addItem(name); 20 System.out.println("Do you have another team to add? true/false"); 21 moreTeamsToAdd = snr.nextBoolean(); 22 snr.nextLine();//rember to add one last nextLine() if 23 //you have a loop ending with snr.nextBoolean or nextInt, or nextDouble 24 }

Consider the above code segment. It is necessary to include a seemingly redundant nextLine( ) method at the end of the loop.

**When**:

You don't need to understand the "why"s of this (though it will be explained below), but you need to be aware of "when" to do this. It's at the end of any loop in which that last Scanner reading from the user is a nextInt( ), nextDouble( ), nextBoolean( ) etc. But not nextLine( ).

**Why**:

This is a little hard to understand, but you need to realize first of all that there are invisible ASCII and UNICODE characters, like Tab, and Space, and also Enter (what used to be called "carriage return", harkening back to manual type writers). Pressing the "Enter" key yeilds the 'Enter' character (it's actually ASCII code character # 13, remembering that 'A' is # 65, 'B' is # 66, etc.)

The Scanner method nextLine( ) takes **both** the next String in the stream (including spaces), and also the 'Enter' character. This is why the insertion point moves to the next line. And, by the way, the Scanner method next( ) reads in only the next String in the stream (including spaces), which is coming from the keyboard of the system, and leaves the 'Enter' character.

With nextBoolean( )/nextInt( )/nextDouble( ), it's also the case that the final 'Enter' character remains "hanging", and doesn't get used until the next input line. That next input line thus takes in as input that 'Enter' character, and what we see is the insertion point skipping a blank line, but even more problematically skipping over the next intended input.

The solution is to put in an extra nextLine( ) - the method that takes the String input **and** the 'Enter' character - as one last line in the loop, to "gobble up" that "hanging" 'Enter' key.