Using static methods, if statements, and comparison operators

In this exercise you will pratice using static methods (i.e. functions), and if statements

A Coin Flip Program

Use BlueJ to create a new project Lab2 inside your U: drive (or anywhere if you are using your personal computer), then create a new java class called CoinFlip inside of it. Don't forget the preamble:

//Name: TODO:

//Approximate time to complete: TODO:

//References: TODO:

If you forgot how to create a blank Java program, refer back to the programs you have already written or the previous lab.

First we will outline our plan for the program by writing some comments inside the "main" part where we will later fill in some programming code (don't forget the indenting):

		//Get a random number
		//Decide the outcome of a coin flip
		//Get a second random number
		//Decide the outcome of a second coin flip
		//Print out which flip had a higher score
		//Print out the maximum of the two flips

There is a lot of functionality in Java that has already been programmed in, and can be accessed through the Java API (Application Programming Interface). The API is fully documented through webpages called Javadocs. For example, in the API page for the Math class, there is a section called "Method Summary", which contains the following line (among many other things).

static doublerandom()
          Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

The fact that this line appears under the "Method Summary" and that the word static appears on the left indicates that this method is something called a static method. A static method acts as a function, possibly taking some kind of input, doing some internal operations, and then producing some output. In this case, it doesn't require any input, since the point is just to ask for a random decimal number between 0 and 1. The word double after static indicates that the output data is of type double.

To use a static method, type the name of the class (in this case, Math), followed by a period, the name of the method, and a pair of parentheses. In this case, we are also getting output back from the call to the method, so we will store the result in a variable of the same type, like this:

		//Get a random number
		double myNumber;
		myNumber = Math.random();
		

You might imagine that the phrase Math.random() momentarily "becomes" a random number whenever the line is executed.

Now we will print out "heads" or "tails". We want equal odds of both, and one way of doing this is to use two if statements:

		//Decide the outcome of a coin flip
		if (myNumber < .5) {
			System.out.println("heads");
		}
		if (myNumber >= .5) {
			System.out.println("tails");
		}
		

When Java gets to the first if statement in the course of running your program, it decides whether or not the condition (myNumber < .5) is true or false. If it is true, it runs any statements contained in the following code block (between the { and the }). If it is false, then it skips over it. Put this in and try running your program a few times, and it should behave as you expect: sometimes saying heads, sometimes tails. Here is a rundown of the ways you can compare numbers in Java (note that we use two equal signs to test for equality, whereas one equal sign is used to change the value of a variable):

comparison operator meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== (exactly) equal to
!= not equal to

A simpler way of solving this same problem is to use a single, more elaborate if statement instead of two separate if statements. Remove the two if statements and replace them with the following:

		//Decide the outcome of a coin flip

		if (myNumber < .5) {
			System.out.println("heads");
		}
		else {
			System.out.println("tails");
		}
		

Note that the else doesn't get any condition to test. These 6 lines of code are all actually a single if statement. When the program is run, Java will still evaluate the first 3 lines in the same way as before. However, the code block after the else is only executed if the condition (myNumber < .5) is false. If you compile and run your code again, it should be behaving the same as before (sometimes heads, sometimes tails).

Now suppose we want to allow for several different outcomes. We will also assign a score for each outcome (imagine this is part of some sort of game). We will figure for a 40% chance of heads, a 40% chance of tails, a 5% chance of landing on the edge, and a 15% chance of falling off the table when the coin is tosssed. Change the if-else code above to the following:

		//Decide the outcome of a coin flip
		int score;
		if (myNumber < .4) {
			System.out.println("heads");
			score = 5;
		}
		else if (myNumber < .8) {
			System.out.println("tails");
			score = 2;
		}
		else if (myNumber < .85) {
			System.out.println("landed on the edge!");
			score = 20;
		}
		else {
			System.out.println("fell off the table");
			score = -3;
		}

		System.out.println("Score for the flip was: " + score);
		

Be sure you understand how this works: the 4 sections (if,    else if,    else if,    else) all comprise a single if statement. If the condition (myNumber < .4) is true, then it prints out heads, assigns 5 to the variable score, and skips all the way down to next line after the else block. If it was false, then Java tries the first else if condition, (myNumber < .8). If that turns out to be true, it executes the following block, printing out tails, and skips to the bottom. If false, then it tries the next else if condition. If all 3 conditions turn out to be false, then the else block is executed. This can only happen if myNumber is at least .85, leaving a 15% chance of the coin falling off the table.

In short, exactly one of the 4 code blocks above will be executed, depending on the value of myNumber. Compile your code, and then run the program a few times. Make sure it all makes sense to you.

Now add in some code that makes a second coin flip occur (be sure to use another call to random() because if you reuse the old random number then you will get the same result again)! Make up another variable to store that new random number. Store the score corresponding to the second coin in an integer variable called secondScore, using the same scoring scheme. Compile and run your code to make sure it works correctly.

Now print out which coin flip had a higher score (or say that they were equal), using another if statement. This would go below your comment that says //Print out which flip had a higher score. Your program should now look something like this when you run it:

heads
Score for the flip was: 5
heads
Score for the second flip was: 5
Both flips had the same score

Or maybe like this, depending on how the flips turn out:

fell off the table
Score for the flip was: -3
tails
Score for the second flip was: 2
The second flip had the higher score

Now we will use a static method to print out the maximum of the two scores. Referring back to the API page for the Math class, find the following line.

static intmax(int a, int b)
          Returns the greater of two int values.

The int a and int b that appear in between the parentheses indicate that we are to supply two int values as input. The int at the far left indicates that this method returns an int value. So here is how we would use that method (add the following to the end of your program):

		int maxScore = Math.max(score, secondScore);

Now print out the variable maxScore. Your program should look something like the printout below when you run it. Run it a few times to make sure it's getting results that make sense. Also make sure to fill in the 3 comments at the very top of your program if you haven't done so yet.

landed on the edge!
Score for the flip was: 20
tails
Score for the second flip was: 2
The first flip had the higher score
The higher score was: 20