Java Reference
In-Depth Information
int
x=(
int
) (Math . random ( )
∗
10) ;
int
y=(
int
) (Math . random ( )
∗
10) ;
Scanner keyboard =
new
Scanner(System. in) ;
System. out . print (x +
"*"
+y+
"="
);
int
z = keyboard . nextInt () ;
if
(z == x
∗
y)
{
System. out . println (
"Congratulations!"
);
}
else
{
System. out . println (
"You need more practice"
);
}
}
}
Note how the start of a block and the closing brace at the end of the block should
be aligned. Remember that we can always select the
Source
-
Format
menu in NetBeans to
format our code.
2.4 Combining Conditions
Our next program calculates the grade of a student. It takes as input the student's
numerical grade and it converts it to a letter grade. Here is the algorithm that we will use.
1. Ask the user to enter grade as number.
2. Read the number in variable
x
.
3. Declare a variable
grade
.
4. If
x>
=90and
x<
= 100, then set grade to be equal to
A
.
'
'
5. If
x>
=80and
x<
90, then set grade to be equal to
B
.
'
'
6. If
x>
=70and
x<
80, then set grade to be equal to
C
.
'
'
7. If
x>
=60and
x<
70, then set grade to be equal to
D
.
'
'
8. If
x<
60, then set grade to be equal to
F
.
'
'
Steps 1-3 are easy. A possible implementation follows.
System. out . print (
"Enter numeric grade: "
);
int
x;
Scanner keyboard =
new
Scanner(System. in) ;
x = keyboard . nextInt () ;
char
grade ;
Next, we need to check if the grade is between 90 and 100. We can do this using two
nested
if
statements.
if
(x
>
= 90)
{
if
(x
<
= 100)
{
grade =
;
'A'
}
}