Sunday 3 July 2016

Chapter 4 Exercise 14, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*4.14 (Convert letter grade to number) Write a program that prompts the user to enter a letter grade A, B, C, D, or F and displays 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 ProgrammingEx4_14 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter a letter grade: ");
  String s = input.nextLine();
 
  if (s.length() != 1) {
   System.out.println("You must enter exactly one character");
   System.exit(1);
  }
 
  char ch = s.charAt(0);
  int i = 0;
  switch (ch) {
  case 'A':
   i = 4;
   break;
  case 'B':
   i = 3;
   break;
  case 'C':
   i = 2;
   break;
  case 'D':
   i = 1;
   break;
  case 'F':
   i = 0;
   break;
 
  default:
   System.out.println(s + " is an invalid grade");
   System.exit(1);
   break;
  }
 
  System.out.println("The numeric value for grade " + s + " is " + i);
 
 }
 
}

No comments :

Post a Comment