SlideShare una empresa de Scribd logo
1 de 7
Descargar para leer sin conexión
CS4-1
CASESTUDY
4 The SerialNumber Class
In this case study you examine the SerialNumber class, which is used by the Home Soft-
ware Company to validate software serial numbers. A valid software serial number is in
the form LLLLL-DDDD-LLLL, where L indicates an alphabetic letter and D indicates a numeric
digit. For example, WRXTQ-7786-PGVZ is a valid serial number. Notice that a serial number
consists of three groups of characters, delimited by hyphens. Figure CS4-1 shows a UML
diagram for the SerialNumber class.
Figure CS4-1 UML diagram for the SerialNumber class
The fields first, second, and third are used to hold the first, second, and third groups of
characters in a serial number. The valid field is set to true by the constructor to indicate a
valid serial number, or false to indicate an invalid serial number. Table CS4-1 describes
the class’s methods.
CS4-2 Case Study 4 The SerialNumber Class
Table CS4-1 SerialNumber class’s methods
Method Description
Constructor The constructor accepts a string argument that contains a serial number.
The string is tokenized and its tokens are stored in the first, second,
and third fields. The validate method is called.
isValid This method returns the value in the valid field.
validate This method calls the isFirstGroupValid, isSecondGroupValid, and
isThirdGroupValid methods to validate the first, second, and third
fields.
isFirstGroupValid This method returns true if the value stored in the first field is valid.
Otherwise, it returns false.
isSecondGroupValid This method returns true if the value stored in the second field is valid.
Otherwise, it returns false.
isThirdGroupValid This method returns true if the value stored in the third field is valid.
Otherwise, it returns false.
The code for the SerialNumber class is shown in Code Listing CS4-1.
Code Listing CS4-1 (SerialNumber.java)
1 import java.util.StringTokenizer;
2
3 /**
4 * The SerialNumber class takes a software serial number in
5 * the form of LLLLL-DDDD-LLLL where each L is a letter
6 * and each D is a digit. The serial number has three groups
7 * of characters, separated by hyphens. The class extracts
8 * the three groups of characters and validates them.
9 */
10
11 public class SerialNumber
12 {
13 private String first; // First group of characters
14 private String second; // Second group of characters
15 private String third; // Third group of characters
16 private boolean valid; // Flag indicating validity
17
18 /**
19 * The following constructor accepts a serial number as
20 * its String argument. The argument is broken into
21 * three groups and each group is validated.
22 */
23
Case Study 4 The SerialNumber Class CS4-3
24 public SerialNumber(String sn)
25 {
26 // Create a StringTokenizer and initialize
27 // it with a trimmed copy of sn.
28 StringTokenizer st =
29 new StringTokenizer(sn.trim(), "-");
30
31 // Tokenize and validate.
32 if (st.countTokens() != 3)
33 valid = false;
34 else
35 {
36 first = st.nextToken();
37 second = st.nextToken();
38 third = st.nextToken();
39 validate();
40 }
41 }
42
43 /**
44 * The following method returns the valid field.
45 */
46
47 public boolean isValid()
48 {
49 return valid;
50 }
51
52 /**
53 * The following method sets the valid field to true
54 * if the serial number is valid. Otherwise it sets
55 * valid to false.
56 */
57
58 private void validate()
59 {
60 if (isFirstGroupValid() && isSecondGroupValid() &&
61 isThirdGroupValid())
62 valid = true;
63 else
64 valid = false;
65 }
66
67 /**
68 * The following method validates the first group of
69 * characters. If the group is valid, it returns
70 * true. Otherwise it returns false.
71 */
CS4-4 Case Study 4 The SerialNumber Class
72
73 private boolean isFirstGroupValid()
74 {
75 boolean groupGood = true; // Flag
76 int i = 0; // Loop control variable
77
78 // Check the length of the group.
79 if (first.length() != 5)
80 groupGood = false;
81
82 // See if each character is a letter.
83 while (groupGood && i < first.length())
84 {
85 if (!Character.isLetter(first.charAt(i)))
86 groupGood = false;
87 i++;
88 }
89
90 return groupGood;
91 }
92
93 /**
94 * The following method validates the second group
95 * of characters. If the group is valid, it returns
96 * true. Otherwise it returns false.
97 */
98
99 private boolean isSecondGroupValid()
100 {
101 boolean groupGood = true; // Flag
102 int i = 0; // Loop control variable
103
104 // Check the length of the group.
105 if (second.length() != 4)
106 groupGood = false;
107
108 // See if each character is a digit.
109 while (groupGood && i < second.length())
110 {
111 if (!Character.isDigit(second.charAt(i)))
112 groupGood = false;
113 i++;
114 }
115
116 return groupGood;
117 }
118
Case Study 4 The SerialNumber Class CS4-5
119 /**
120 * The following method validates the third group of
121 * characters. If the group is valid, it returns
122 * true. Otherwise it returns false.
123 */
124
125 private boolean isThirdGroupValid()
126 {
127 boolean groupGood = true; // Flag
128 int i = 0; // Loop control variable
129
130 // Check the length of the group.
131 if (third.length() != 4)
132 groupGood = false;
133
134 // See if each character is a letter.
135 while (groupGood && i < third.length())
136 {
137 if (!Character.isLetter(third.charAt(i)))
138 groupGood = false;
139 i++;
140 }
141
142 return groupGood;
143 }
144 }
Let’s take a closer look at the constructor, in lines 24 through 41. The following statement, in
lines 28 and 29, creates a StringTokenizer object, using the hyphen character as a delimiter:
StringTokenizer st =
new StringTokenizer(sn.trim(), "-");
Notice that we call the argument’s trim method to remove any leading and/or trailing
whitespace characters. This is important because whitespace characters are not used as
delimiters in this code. If the argument contains leading whitespace characters, they will be
included as part of the first token. Trailing whitespace characters will be included as part
of the last token.
Next, the if statement in lines 32 through 40 executes:
if (st.countTokens() != 3)
valid = false;
else
{
first = st.nextToken();
second = st.nextToken();
third = st.nextToken();
validate();
}
CS4-6 Case Study 4 The SerialNumber Class
A valid serial number must have three groups of characters, so the if statement determines
whether the string has three tokens. If not, the valid field is set to false. Otherwise, the
three tokens are extracted and assigned to the first, second, and third fields. Last, the
validate method is called. The validate method calls the isFirstGroupValid,
isSecondGroupValid, and isThirdGroupValid methods to validate the three groups of
characters. In the end, the valid field will be set to true if the serial number is valid, or
false otherwise. The program in Code Listing CS4-2 demonstrates the class.
Code Listing CS4-2 (SerialNumberTester.java)
1 /**
2 * This program demonstrates the SerialNumber class.
3 */
4
5 public class SerialNumberTester
6 {
7 public static void main(String[] args)
8 {
9 String serial1 = "GHTRJ-8975-AQWR"; // Valid
10 String serial2 = "GHT7J-8975-AQWR"; // Invalid
11 String serial3 = "GHTRJ-8J75-AQWR"; // Invalid
12 String serial4 = "GHTRJ-8975-AQ2R"; // Invalid
13
14 // Validate serial1.
15
16 SerialNumber sn = new SerialNumber(serial1);
17 if (sn.isValid())
18 System.out.println(serial1 + " is valid.");
19 else
20 System.out.println(serial1 + " is invalid.");
21
22 // Validate serial2.
23
24 sn = new SerialNumber(serial2);
25 if (sn.isValid())
26 System.out.println(serial2 + " is valid.");
27 else
28 System.out.println(serial2 + " is invalid.");
29
30 // Validate serial3.
31
32 sn = new SerialNumber(serial3);
33 if (sn.isValid())
34 System.out.println(serial3 + " is valid.");
35 else
36 System.out.println(serial3 + " is invalid.");
37
Case Study 4 The SerialNumber Class CS4-7
38 // Validate serial4.
39
40 sn = new SerialNumber(serial4);
41 if (sn.isValid())
42 System.out.println(serial4 + " is valid.");
43 else
44 System.out.println(serial4 + " is invalid.");
45 }
46 }
Program Output
GHTRJ-8975-AQWR is valid.
GHT7J-8975-AQWR is invalid.
GHTRJ-8J75-AQWR is invalid.
GHTRJ-8975-AQ2R is invalid.

Más contenido relacionado

La actualidad más candente (6)

Number system
Number systemNumber system
Number system
 
Telephone call-simulation
Telephone call-simulationTelephone call-simulation
Telephone call-simulation
 
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KRLoops IN COMPUTER SCIENCE STANDARD 11 BY KR
Loops IN COMPUTER SCIENCE STANDARD 11 BY KR
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
Python Style Guide
Python Style GuidePython Style Guide
Python Style Guide
 

Similar a Serial number java_code

Answer using basic programming beginner knowledge pls...........Othe.pdf
Answer using basic programming beginner knowledge pls...........Othe.pdfAnswer using basic programming beginner knowledge pls...........Othe.pdf
Answer using basic programming beginner knowledge pls...........Othe.pdf
suresh640714
 
I am working on java programming that converts zipcode to barcode an.pdf
I am working on java programming that converts zipcode to barcode an.pdfI am working on java programming that converts zipcode to barcode an.pdf
I am working on java programming that converts zipcode to barcode an.pdf
thangarajarivukadal
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
pranav kumar verma
 
Can someone help me with this code When I run it, it stops after th.pdf
Can someone help me with this code When I run it, it stops after th.pdfCan someone help me with this code When I run it, it stops after th.pdf
Can someone help me with this code When I run it, it stops after th.pdf
Amansupan
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
Princess Sam
 

Similar a Serial number java_code (19)

LectureNotes-05-DSA
LectureNotes-05-DSALectureNotes-05-DSA
LectureNotes-05-DSA
 
Analyzing the Quake III Arena GPL project
Analyzing the Quake III Arena GPL projectAnalyzing the Quake III Arena GPL project
Analyzing the Quake III Arena GPL project
 
Answer using basic programming beginner knowledge pls...........Othe.pdf
Answer using basic programming beginner knowledge pls...........Othe.pdfAnswer using basic programming beginner knowledge pls...........Othe.pdf
Answer using basic programming beginner knowledge pls...........Othe.pdf
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Sas array statement
Sas array statementSas array statement
Sas array statement
 
Visual Programing basic lectures 7.pptx
Visual Programing basic lectures  7.pptxVisual Programing basic lectures  7.pptx
Visual Programing basic lectures 7.pptx
 
Array assignment
Array assignmentArray assignment
Array assignment
 
3.ArraysandPointers.pptx
3.ArraysandPointers.pptx3.ArraysandPointers.pptx
3.ArraysandPointers.pptx
 
C# basics
C# basicsC# basics
C# basics
 
Array and Collections in c#
Array and Collections in c#Array and Collections in c#
Array and Collections in c#
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Ch08
Ch08Ch08
Ch08
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
 
I am working on java programming that converts zipcode to barcode an.pdf
I am working on java programming that converts zipcode to barcode an.pdfI am working on java programming that converts zipcode to barcode an.pdf
I am working on java programming that converts zipcode to barcode an.pdf
 
Exploring collections with example
Exploring collections with exampleExploring collections with example
Exploring collections with example
 
Can someone help me with this code When I run it, it stops after th.pdf
Can someone help me with this code When I run it, it stops after th.pdfCan someone help me with this code When I run it, it stops after th.pdf
Can someone help me with this code When I run it, it stops after th.pdf
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Lec 25 - arrays-strings
Lec 25 - arrays-stringsLec 25 - arrays-strings
Lec 25 - arrays-strings
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 

Más de Shyam Sarkar

Scry analytics article on data analytics outsourcing, nov. 18, 2014
Scry analytics article on data analytics outsourcing, nov. 18, 2014Scry analytics article on data analytics outsourcing, nov. 18, 2014
Scry analytics article on data analytics outsourcing, nov. 18, 2014
Shyam Sarkar
 
Decision tree handson
Decision tree handsonDecision tree handson
Decision tree handson
Shyam Sarkar
 
Forrester big data_predictive_analytics
Forrester big data_predictive_analyticsForrester big data_predictive_analytics
Forrester big data_predictive_analytics
Shyam Sarkar
 
Stock markets and_human_genomics
Stock markets and_human_genomicsStock markets and_human_genomics
Stock markets and_human_genomics
Shyam Sarkar
 
Cancer genome repository_berkeley
Cancer genome repository_berkeleyCancer genome repository_berkeley
Cancer genome repository_berkeley
Shyam Sarkar
 
Big security for_big_data
Big security for_big_dataBig security for_big_data
Big security for_big_data
Shyam Sarkar
 
Renewable energy report
Renewable energy reportRenewable energy report
Renewable energy report
Shyam Sarkar
 
Wef big databigimpact_briefing_2012
Wef big databigimpact_briefing_2012Wef big databigimpact_briefing_2012
Wef big databigimpact_briefing_2012
Shyam Sarkar
 

Más de Shyam Sarkar (20)

Scry analytics article on data analytics outsourcing, nov. 18, 2014
Scry analytics article on data analytics outsourcing, nov. 18, 2014Scry analytics article on data analytics outsourcing, nov. 18, 2014
Scry analytics article on data analytics outsourcing, nov. 18, 2014
 
Tagores russiar chithi_paper
Tagores russiar chithi_paperTagores russiar chithi_paper
Tagores russiar chithi_paper
 
Decision tree handson
Decision tree handsonDecision tree handson
Decision tree handson
 
Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014Cancer genomics big_datascience_meetup_july_14_2014
Cancer genomics big_datascience_meetup_july_14_2014
 
Technology treasury-management-2013
Technology treasury-management-2013Technology treasury-management-2013
Technology treasury-management-2013
 
UN-Creative economy-report-2013
UN-Creative economy-report-2013UN-Creative economy-report-2013
UN-Creative economy-report-2013
 
Local exchanges for_sm_es
Local exchanges for_sm_esLocal exchanges for_sm_es
Local exchanges for_sm_es
 
Innovative+agricultural+sme+finance+models
Innovative+agricultural+sme+finance+modelsInnovative+agricultural+sme+finance+models
Innovative+agricultural+sme+finance+models
 
Religionofman
ReligionofmanReligionofman
Religionofman
 
Forrester big data_predictive_analytics
Forrester big data_predictive_analyticsForrester big data_predictive_analytics
Forrester big data_predictive_analytics
 
Stock markets and_human_genomics
Stock markets and_human_genomicsStock markets and_human_genomics
Stock markets and_human_genomics
 
Cancer genome repository_berkeley
Cancer genome repository_berkeleyCancer genome repository_berkeley
Cancer genome repository_berkeley
 
Big security for_big_data
Big security for_big_dataBig security for_big_data
Big security for_big_data
 
Renewable energy report
Renewable energy reportRenewable energy report
Renewable energy report
 
Nasa on biofuel
Nasa on biofuelNasa on biofuel
Nasa on biofuel
 
Wef big databigimpact_briefing_2012
Wef big databigimpact_briefing_2012Wef big databigimpact_briefing_2012
Wef big databigimpact_briefing_2012
 
World bank report
World bank reportWorld bank report
World bank report
 
Green technology report_2012
Green technology report_2012Green technology report_2012
Green technology report_2012
 
Portfolio investment opportuities in india
Portfolio investment opportuities in indiaPortfolio investment opportuities in india
Portfolio investment opportuities in india
 
Tapan 29 jun
Tapan 29 junTapan 29 jun
Tapan 29 jun
 

Último

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 

Último (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

Serial number java_code

  • 1. CS4-1 CASESTUDY 4 The SerialNumber Class In this case study you examine the SerialNumber class, which is used by the Home Soft- ware Company to validate software serial numbers. A valid software serial number is in the form LLLLL-DDDD-LLLL, where L indicates an alphabetic letter and D indicates a numeric digit. For example, WRXTQ-7786-PGVZ is a valid serial number. Notice that a serial number consists of three groups of characters, delimited by hyphens. Figure CS4-1 shows a UML diagram for the SerialNumber class. Figure CS4-1 UML diagram for the SerialNumber class The fields first, second, and third are used to hold the first, second, and third groups of characters in a serial number. The valid field is set to true by the constructor to indicate a valid serial number, or false to indicate an invalid serial number. Table CS4-1 describes the class’s methods.
  • 2. CS4-2 Case Study 4 The SerialNumber Class Table CS4-1 SerialNumber class’s methods Method Description Constructor The constructor accepts a string argument that contains a serial number. The string is tokenized and its tokens are stored in the first, second, and third fields. The validate method is called. isValid This method returns the value in the valid field. validate This method calls the isFirstGroupValid, isSecondGroupValid, and isThirdGroupValid methods to validate the first, second, and third fields. isFirstGroupValid This method returns true if the value stored in the first field is valid. Otherwise, it returns false. isSecondGroupValid This method returns true if the value stored in the second field is valid. Otherwise, it returns false. isThirdGroupValid This method returns true if the value stored in the third field is valid. Otherwise, it returns false. The code for the SerialNumber class is shown in Code Listing CS4-1. Code Listing CS4-1 (SerialNumber.java) 1 import java.util.StringTokenizer; 2 3 /** 4 * The SerialNumber class takes a software serial number in 5 * the form of LLLLL-DDDD-LLLL where each L is a letter 6 * and each D is a digit. The serial number has three groups 7 * of characters, separated by hyphens. The class extracts 8 * the three groups of characters and validates them. 9 */ 10 11 public class SerialNumber 12 { 13 private String first; // First group of characters 14 private String second; // Second group of characters 15 private String third; // Third group of characters 16 private boolean valid; // Flag indicating validity 17 18 /** 19 * The following constructor accepts a serial number as 20 * its String argument. The argument is broken into 21 * three groups and each group is validated. 22 */ 23
  • 3. Case Study 4 The SerialNumber Class CS4-3 24 public SerialNumber(String sn) 25 { 26 // Create a StringTokenizer and initialize 27 // it with a trimmed copy of sn. 28 StringTokenizer st = 29 new StringTokenizer(sn.trim(), "-"); 30 31 // Tokenize and validate. 32 if (st.countTokens() != 3) 33 valid = false; 34 else 35 { 36 first = st.nextToken(); 37 second = st.nextToken(); 38 third = st.nextToken(); 39 validate(); 40 } 41 } 42 43 /** 44 * The following method returns the valid field. 45 */ 46 47 public boolean isValid() 48 { 49 return valid; 50 } 51 52 /** 53 * The following method sets the valid field to true 54 * if the serial number is valid. Otherwise it sets 55 * valid to false. 56 */ 57 58 private void validate() 59 { 60 if (isFirstGroupValid() && isSecondGroupValid() && 61 isThirdGroupValid()) 62 valid = true; 63 else 64 valid = false; 65 } 66 67 /** 68 * The following method validates the first group of 69 * characters. If the group is valid, it returns 70 * true. Otherwise it returns false. 71 */
  • 4. CS4-4 Case Study 4 The SerialNumber Class 72 73 private boolean isFirstGroupValid() 74 { 75 boolean groupGood = true; // Flag 76 int i = 0; // Loop control variable 77 78 // Check the length of the group. 79 if (first.length() != 5) 80 groupGood = false; 81 82 // See if each character is a letter. 83 while (groupGood && i < first.length()) 84 { 85 if (!Character.isLetter(first.charAt(i))) 86 groupGood = false; 87 i++; 88 } 89 90 return groupGood; 91 } 92 93 /** 94 * The following method validates the second group 95 * of characters. If the group is valid, it returns 96 * true. Otherwise it returns false. 97 */ 98 99 private boolean isSecondGroupValid() 100 { 101 boolean groupGood = true; // Flag 102 int i = 0; // Loop control variable 103 104 // Check the length of the group. 105 if (second.length() != 4) 106 groupGood = false; 107 108 // See if each character is a digit. 109 while (groupGood && i < second.length()) 110 { 111 if (!Character.isDigit(second.charAt(i))) 112 groupGood = false; 113 i++; 114 } 115 116 return groupGood; 117 } 118
  • 5. Case Study 4 The SerialNumber Class CS4-5 119 /** 120 * The following method validates the third group of 121 * characters. If the group is valid, it returns 122 * true. Otherwise it returns false. 123 */ 124 125 private boolean isThirdGroupValid() 126 { 127 boolean groupGood = true; // Flag 128 int i = 0; // Loop control variable 129 130 // Check the length of the group. 131 if (third.length() != 4) 132 groupGood = false; 133 134 // See if each character is a letter. 135 while (groupGood && i < third.length()) 136 { 137 if (!Character.isLetter(third.charAt(i))) 138 groupGood = false; 139 i++; 140 } 141 142 return groupGood; 143 } 144 } Let’s take a closer look at the constructor, in lines 24 through 41. The following statement, in lines 28 and 29, creates a StringTokenizer object, using the hyphen character as a delimiter: StringTokenizer st = new StringTokenizer(sn.trim(), "-"); Notice that we call the argument’s trim method to remove any leading and/or trailing whitespace characters. This is important because whitespace characters are not used as delimiters in this code. If the argument contains leading whitespace characters, they will be included as part of the first token. Trailing whitespace characters will be included as part of the last token. Next, the if statement in lines 32 through 40 executes: if (st.countTokens() != 3) valid = false; else { first = st.nextToken(); second = st.nextToken(); third = st.nextToken(); validate(); }
  • 6. CS4-6 Case Study 4 The SerialNumber Class A valid serial number must have three groups of characters, so the if statement determines whether the string has three tokens. If not, the valid field is set to false. Otherwise, the three tokens are extracted and assigned to the first, second, and third fields. Last, the validate method is called. The validate method calls the isFirstGroupValid, isSecondGroupValid, and isThirdGroupValid methods to validate the three groups of characters. In the end, the valid field will be set to true if the serial number is valid, or false otherwise. The program in Code Listing CS4-2 demonstrates the class. Code Listing CS4-2 (SerialNumberTester.java) 1 /** 2 * This program demonstrates the SerialNumber class. 3 */ 4 5 public class SerialNumberTester 6 { 7 public static void main(String[] args) 8 { 9 String serial1 = "GHTRJ-8975-AQWR"; // Valid 10 String serial2 = "GHT7J-8975-AQWR"; // Invalid 11 String serial3 = "GHTRJ-8J75-AQWR"; // Invalid 12 String serial4 = "GHTRJ-8975-AQ2R"; // Invalid 13 14 // Validate serial1. 15 16 SerialNumber sn = new SerialNumber(serial1); 17 if (sn.isValid()) 18 System.out.println(serial1 + " is valid."); 19 else 20 System.out.println(serial1 + " is invalid."); 21 22 // Validate serial2. 23 24 sn = new SerialNumber(serial2); 25 if (sn.isValid()) 26 System.out.println(serial2 + " is valid."); 27 else 28 System.out.println(serial2 + " is invalid."); 29 30 // Validate serial3. 31 32 sn = new SerialNumber(serial3); 33 if (sn.isValid()) 34 System.out.println(serial3 + " is valid."); 35 else 36 System.out.println(serial3 + " is invalid."); 37
  • 7. Case Study 4 The SerialNumber Class CS4-7 38 // Validate serial4. 39 40 sn = new SerialNumber(serial4); 41 if (sn.isValid()) 42 System.out.println(serial4 + " is valid."); 43 else 44 System.out.println(serial4 + " is invalid."); 45 } 46 } Program Output GHTRJ-8975-AQWR is valid. GHT7J-8975-AQWR is invalid. GHTRJ-8J75-AQWR is invalid. GHTRJ-8975-AQ2R is invalid.