Explanation of the Code, part 2:
(Note: don’t rely on this image for the code, because I could not fit it all into one image). Now I will explain the CPU class! By the way, if you have any questions about what any of this terminology is, there is a great tutorial here about understanding OOP, created by the makers of Java.
The first method is called comparemoves. Guess what it does? (Compares moves!). Inside are a bunch of if statements. Some of these are inside of each other, which might seem a little weird. Basically, all it does is see if the user played rock, paper, or scissors. Once it finds out which one he/she played, a bunch of if statements inside that find out what the CPU played and tell a different method, outputmoves, what to print on the screen.
Note that this method is called public void comparemoves. Void means that when it’s called, it doesn’t return anything. Returning a value means that the function passes back a value to the instruction that called it. The line String CPUMove = cpu1.getCPUMove(); takes what was returned from the method getCPUMove in cpu1 and puts it in the string CPUMove. Make sense?
Now let’s talk about the outputmoves method, which the comparemoves method calls. All it does is put together a string, output, and print it to the console, where you typed your moves earlier. The System.out.println statement is pretty simple, as all it does is print the string output. The String output = ... statement might be a bit confusing, however. It seems pretty normal, but what’s this concat() thing? It’s a method that concatentates (fancy word for “pins onto the end”) the thing in parentheses to the string before it.
This helps us put together the sentence “I played . !” using the parameters that were passed to it (things that were given to it to work with).
Finally, we reach the getCPUMove method. This method randomly chooses what move the computer plays. The first line chooses a random number from just above 0 to just below 3. Then, the number is floored, or the decimal part is removed, making it a random integer from 0 to 2. Finally, it is cast (changed) to an integer type (it wasn’t completely an integer before because of the fractional part), and is stored into choice. Next, a string rpsmove is created and set to nothing (“”). Finally, there is a switch statement, which is a variant of the if statement.
All that it says is if choice equals 0, then rpsmove = "rock". If it equals 1, it is set to “paper”, and if it is none of those (it must be 2), it is set to “scissors”. Then it returns the move in the string rpsmove. Voilà! We’ve returned a random move from the computer! But before I finish, I’d like to point out some things about the switch statement. Notice that the variable being tested is inside the parentheses next to the word switch, and that there are break statements after each case. All these do is clear the path for the next case. OK! We’re done!