Java Reference
In-Depth Information
import java . util . ;
public class Grade {
public static void main(String [] args)
{
int x;
char c= 'O' ;
System. out . println ( "Enter numeric grade: " );
Scanner keyboard = new Scanner(System. in) ;
x = keyboard . nextInt () ;
if (x < = 100 && x > = 90) {
c= 'A' ;
if (x < 90 && x > = 80) {
c=
;
'B'
if (x
<
80 && x
>
= 70)
{
;
if (x < 70 && x > = 60) {
c= 'D' ;
if (x < 60 && x > =0) {
c= 'F' ;
System. out . println ( "Your letter grade is: " +c ) ;
c=
'C'
}
}
Note that the variable c needs to be given a default value. If it is not, then the last line
of the code (i.e., the line that does the final printing) will have an error. The reason is that
it is possible that not a single if condition fires. In this case, the value of c will not be
defined and Java will not know what to print. Note as well that the Java compiler is not
very smart. Even if it is logically the case that one of the if conditions must always be true,
Java will not be able to determine this. Therefore, it is a good idea to give a default value
to every variable. The above program will report grade of O when the grade is not between
0 and 100.
2.5 The String Class
Next, let us consider the reverse problem. The user enters the letter grade and the
program presents the numeric grade. Here is a possible algorithm to solve the problem.
1. Ask the user to enter the grade as a string.
2. Save the result in the string s .
3. If s is equal to "A" , then tell the user the grade is between 90 and 100.
4. If s is equal to "B" , then tell the user the grade is between 80 and 90.
5. If s is equal to "C" , then tell the user the grade is between 70 and 80.
6. If s is equal to "D" , then tell the user the grade is between 60 and 70.
 
Search WWH ::




Custom Search