Problem:
Write a program that asks the user to enter a product code starting with the form of: NNNNL, where N denotes a number and L a letter. Keep asking the user for a product number until the user enters "XXX". If N > 2000 and L = B, the code is blacklisted and considered as banned.
The main point of this product validator is to be able to handle exceptions in a robust manner. Thus, you are expected to handle two exceptions manually: IndexOutOfBoundsException and NumberFormatException.
At the end of the program, print the total number of attempts, valid codes and banned codes.
Output:
Enter a product code (XXX to quit):
1900G
Enter a product code (XXX to quit):
2500B
Enter a product code (XXX to quit):
1000R
Enter a product code (XXX to quit):
190G
Code of improper length.
Enter a product code (XXX to quit):
190RG
Region is not numeric.
Enter a product code (XXX to quit):
XXX
Total # attempts: 5
# valid codes: 3
# banned codes: 1
1900G
Enter a product code (XXX to quit):
2500B
Enter a product code (XXX to quit):
1000R
Enter a product code (XXX to quit):
190G
Code of improper length.
Enter a product code (XXX to quit):
190RG
Region is not numeric.
Enter a product code (XXX to quit):
XXX
Total # attempts: 5
# valid codes: 3
# banned codes: 1
Solution:
import java.util.Scanner;
public class ProductCodes {
public static void main(String[] args)
{
String code;
Scanner scan = new Scanner(System.in);
char city;
int region, valid = 0, banned = 0,total = 0;
System.out.println("Enter a product code (XXX to quit): ");
code = scan.nextLine();
while (!code.equals("XXX"))
{
try {
total++;
city = code.charAt(4);
region = Integer.parseInt(code.substring(0,4));
valid++;
if (city == 'B' && region >= 2000)
banned++;
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Code of improper length.");
} catch (NumberFormatException e ) {
System.out.println("Region is not numeric.");
} finally {
}
System.out.println("Enter a product code (XXX to quit): ");
code = scan.nextLine();
}
System.out.println("Total # attempts: " + total);
System.out.println(" # valid codes: " + valid);
System.out.println(" # banned codes: " + banned);
}
}
No comments:
Post a Comment