Java if statement convert letter grade to number

Question

We would like to write a program that prompts the user to enter a letter grade A, B, C, D, or F.

Display its corresponding numeric value 4, 3, 2, 1, or 0.

Here is a sample run:

Enter a letter grade: B 
The numeric value for grade B is 3 

Enter a letter grade: T 
T is an invalid grade 
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a letter grade: ");
    char grade = input.nextLine().charAt(0);

    int value = 0;
    // w  w w.j a  v  a 2 s  .com
    //your code here
    
    System.out.println("The numeric value for grade " + grade 
      + " is " + value);
  }  
}



import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a letter grade: ");
    char grade = input.nextLine().charAt(0);

    int value = 0;
    if (Character.toUpperCase(grade) == 'A')
      value = 4;
    else if (Character.toUpperCase(grade) == 'B')
      value = 3;
    else if (Character.toUpperCase(grade) == 'C')
      value = 2;
    else if (Character.toUpperCase(grade) == 'D')
      value = 1;
    else if (Character.toUpperCase(grade) == 'F')
      value = 0;
    else {
      System.out.println(grade + " is an invalid grade");
      System.exit(1);
    }

    System.out.println("The numeric value for grade " + grade 
      + " is " + value);
  }  
}



PreviousNext

Related