The if else if Statement

3.2 The if else if Statement

Sometimes you want to check for a number of related conditions and choose one of several actions. One way to do this is by chaining a series of ifs and elses. Look at the following code segment :
if (x > 0)
{
   System.out.println("x is positive");
}
else if (x < 0)
{
   System.out.println("x is negative");
}
else
{
   System.out.println("x is zero");
}
Following Program determine the grade based on score obtained by student. Score is read by keyboard. Grade is calculated as per conditions:
Score
Grade
90-100
A
80-89
B
70-79
C
50-69
D
0-59
F


import java.util.Scanner;    // Needed for the Scanner class

/**
 *    This program determine grade for a test score.
 */
public class GradeCalc
{
   public static void main(String[] args)
   {
      int  score;    // To hold a test score
      char grade;    // To hold a letter grade

      // Create a Scanner object to read input.
      Scanner console = new Scanner(System.in);

      // Get the test score.
      System.out.print("Enter your numeric test score : ");
      score = console.nextInt();

      // Calculate the grade.
      if (score >= 90)
      {
         grade = 'A';
      }
      else if (score >= 80)
      {
         grade = 'B';
      }
      else if (score >= 70)
      {
         grade = 'C';
      }
      else if (score >= 50)
      {
         grade = 'D';
      }
      else
      {
         grade = 'F';
      }

      // Display the grade.
      System.out.println("Your grade is " + grade);
   }
}
Output 1
Enter your numeric test score : 56
Your grade is D
Output 2
Enter your numeric test score : 89
Your grade is B

No comments:

Post a Comment

Pages