//********************************************************************
//  ProductCodes.java  Listing 10.2 page 536  Author: Lewis/Loftus
//  Modified by Elizabeth Adams
//
//  Demonstrates the use of a try-catch block. 


//********************************************************************

import java.util.Scanner;

public class ProductCodes
{
   //-----------------------------------------------------------------
   //  Counts the number of product codes that are entered with a
   //  zone of R and and district greater than 2000.
   //-----------------------------------------------------------------
   public static void main (String[] args)
   {
      String code;
      char zone;
      int district, numberValid,  numberBanned ;
		Scanner scan;
		
		scan 			 = new Scanner (System.in);
      numberValid  = 0;
		numberBanned = 0;
		
      System.out.print ("Enter product code (XXX to quit): ");
      code = scan.nextLine();
		
         /// "XXX" is a sentinel value to indicate end of data  
	   while (!code.equals ("XXX"))
      {
         try
         {
            zone = code.charAt(9);// looking at 10th element
				// scanner has default delimiters
				// this program can't use Scanner's nextInt() 
				// because there is an 'R' in the string and 'R' is not
				// a default delimiter.
			    // it is possible to explicitly set Scanner's delimiters
            district = Integer.parseInt(code.substring(3, 7));
            numberValid++;
            if (zone == 'R' && district > 2000)
               numberBanned++;
         }
         catch (StringIndexOutOfBoundsException sioobe)
         {
            System.out.println ("Improper code length: " + code);
         }
         catch (NumberFormatException nfe)
         {
			
            System.out.println ("District is not numeric: " + code);
         }

         System.out.print ("Enter product code (XXX to quit): ");
         code = scan.nextLine();
      }

      System.out.println ("# of valid codes entered: " + numberValid);
      System.out.println ("# of banned codes entered: " + numberBanned);
   }
}
// Good features of original program
//   1.  separate handlers for different types of exceptions in the catch blocks
//   2.  specific indication of what caused exception to be thrown

// Poor features of original program
//   1.  variable names banned and valid look to reader like booleans.  They are counters. 
//   2.  initializations and declarations are not separated,,
//   3.  javadocs missing