Java Reference
In-Depth Information
y = 32 + (9.0/5) x;
Recall that the left side of the assignment operation must always be a single variable.
The right side of the assignment operation can be any expression that involves the four
basic arithmetic operations: +, -, *, and /. Parentheses are used to define the order of oper-
ations. In the above example, the parentheses were used to specify that the division should
be performed before the multiplication. Note that division and multiplication have higher
precedence than addition and subtraction. This is why the multiplication in our example is
performed before the addition. Operations with the same precedence (e.g., multiplication
and division) are performed left to right. Therefore, we could have actually omitted the
parentheses and rewritten the code as follows.
y = 32 + 9.0/5
x;
2.3 Random Numbers and the if Statement
Converting degrees Celsius to degrees Fahrenheit was not a real game. However, we
needed this rudimentary example in order to set the stage. We are now ready to create our
first game. Of course, we cannot start right off the bat with a cool game that has graphical
user interface and moving objects; we will save such examples for later. Instead, we will
create a game that helps elementary school students learn the multiplication table. The
program will create two random one-digit numbers and ask the user to multiply them. If
the user gives the correct answer, then the program will congratulate them. However, if
the user does not type the correct response, then the program will suggest that they study
harder. Here is an outline of the steps of the program.
1. Create two random numbers x and y .
2. Display the two random numbers and ask the user to enter the result of x
y .
3. Read the user input in the variable z .
4. If z = x
y , then congratulate the user. Otherwise, ask the user to study harder.
Note that this program is different from our first program in two ways. First, it involves
the generation of a random number. Second, it contains a decision point. Depending on the
user input, the program will take one of two possible routes. In other words, the program
is not going to execute sequentially as our first program.
Create a new project and a new class called Arithmetic . This time, define the class to
be part of the default package. Add the main method and import the library java.util .
You should have the following code.
import java . util . ;
{
public static void main(String [] args)
public class Arithmetic
{
}
}
 
Search WWH ::




Custom Search