Java Reference
In-Depth Information
Note also that the implicit boolean condition of a
switch
statement is based
on equality. The expression at the beginning of the statement is compared to each
case value to determine which one it equals. A
switch
statement cannot be used to
determine other relational operations (such as less than), unless some preliminary
processing is done. For example, the
GradeReport
program in Listing 6.1 prints a
comment based on a numeric grade that is entered by the user.
LISTING 6.1
//********************************************************************
// GradeReport.java Author: Lewis/Loftus
//
// Demonstrates the use of a switch statement.
//********************************************************************
import
java.util.Scanner;
public class
GradeReport
{
//-----------------------------------------------------------------
// Reads a grade from the user and prints comments accordingly.
//-----------------------------------------------------------------
public static void
main (String[] args)
{
int
grade, category;
Scanner scan =
new
Scanner (System.in);
System.out.print ("Enter a numeric grade (0 to 100): ");
grade = scan.nextInt();
category = grade / 10;
System.out.print ("That grade is ");
switch
(category)
{
case
10:
System.out.println ("a perfect score. Well done.");
break
;
case
9:
System.out.println ("well above average. Excellent.");
break
;
case
8:
System.out.println ("above average. Nice job.");
break
;
Search WWH ::
Custom Search