SlideShare a Scribd company logo
1 of 12
Download to read offline
Overview
We will be adding some validation to our Contact classes to prevent bad values from being
stored in the classes. We will also let the user create new contact objects.
Contact Classes
Copy your three contact classes from your last homework to a new project.
Change your Contact class to an abstract class. This will prevent instantiation of Contact objects.
Add an abstract method, public void validate(), to your Contact class.
Validation
Implement the validate() method in your BusinessContact class.
If the name field is the empty string or null, then throw a NullPointerException.
If the age field is not between 1-100, then throw an IllegalStateException
If either of the phone number fields is not exactly 12 characters, then throw an
IllegalStateException
Implement the validate() method in your PersonalContact class.
Validate name and age as described above
If the address or city field is the empty string or null, then throw a NullPointerException.
If the state field is not exactly 2 characters, then throw an IllegalStateException
If the zip code field is not exactly 5 numeric characters, then throw an IllegalStateException
Note: you should not have any try-catch blocks in your contact classes.
Driver Program
Create a driver program that allows a user to create a personal or business contact. Your program
should prompt the user for a contact type:
Create a new contact?
1. Personal
2. Business
2
It should then prompt the user for all details for that contact type:
Name? Susie Grace
Age? 39
Business Phone? 222-333-4444
Cell Phone? 555-666-7777
Call your validate() method to check for bad input and then print out the toString() of your new
contact object.
Name? Susie Grace
Age? 39
Business Phone? 222-333-4444
Cell Phone? 555-666-7777
Business Contact: Susie Grace (39), business - 222-333-4444, cell - 555-666-7777
Validating User Input
Your driver program should have appropriate try-catch blocks to respond to bad user input. This
includes NullPointerExceptions and IllegalStateExceptions. Each exception type should print an
appropriate message to the console.
For example:
Name? Susie Grace
Age? -10
Business Phone? 222-333-4444
Cell Phone? 555-666-7777
Please enter a valid age from 1-100
Another Example:
Name? Susie Grace
Age? 39
Business Phone? 2223334444
Cell Phone? 555-666-7777
Please enter a phone number using the following format: ###-###-####.
Solution
import java.lang.Exception;
import java.util.*;
//Abstract class Contact
abstract class Contact
{
//Instance variable
String name;
int age;
String phoneNo;
//Default constructor to initialize instance variables
Contact()
{
name = null;
age = 0;
phoneNo = null;
}//End of constructor
//Abstract method to validate
abstract int validate();
//Abstract method to accept
abstract void accept();
}//End of abstract class Contact
//Class BusinessContact derived from abstract class Contact
class BusinessContact extends Contact
{
//Instance variable
String businessPhone;
//Default constructor
BusinessContact()
{
//Calls base class constructor
super();
businessPhone = null;
}//End of constructor
//Overrides toString() method to display
public String toString()
{
String msg;
msg = "Business Contact: " + name + "(" + age + ")," + " Business - " +
businessPhone + " Cell - " + phoneNo;
return msg;
}//End of toString() method
//Overrides accept() method
void accept()
{
//Creates a scanner class object
Scanner sc = new Scanner(System.in);
//Accepts data
System.out.println(" Name? ");
name = sc.nextLine();
System.out.println(" Age? ");
age = sc.nextInt();
sc.nextLine();
System.out.println(" Business Phone? ");
businessPhone = sc.nextLine();
System.out.println(" Cell Phone? ");
phoneNo = sc.nextLine();
}//End of accept method
//Overrides validate method
int validate()
{
int flag = 0;
try
{
//Checks if name is zero length
if(name.length() == 0)
throw new NullPointerException();
}
catch(NullPointerException n)
{
System.out.println("Name cannot be left blank");
//Sets the flag to 1
flag = 1;
}
try
{
//Checks age for between 1 - 100
if(age <= 0)
throw new IllegalStateException();
if(age > 100)
throw new IllegalStateException();
}
catch(IllegalStateException ie)
{
System.out.println("Please enter a valid age from 1-100.  Age must be between 1 and
100");
flag = 1;
}
try
{
//Checks phone number length for exactly 12
if(phoneNo.length() != 12)
throw new IllegalStateException();
}
catch(IllegalStateException ie)
{
System.out.println("Please enter a phone number using the following format: ###-###-
####.  Phone number must be 12 character long");
flag = 1;
}
//returns the flag status
return flag;
}//End of method validate
}//End of class Business contact
//class PersonalContact derived from abstract class Contact
class PersonalContact extends Contact
{
//Instance variable
String city, state, zip;
//Default constructor
PersonalContact()
{
//Calls the base class constructor
super();
city = null;
state = null;
zip = null;
}//End of constructor
//Overrides toString() method to display
public String toString()
{
String msg;
msg = "Personal Contact: " + name + "(" + age + ")," + " Cell - " + phoneNo + " City
- " + city + " State - " + state + " Zip - " + zip;
return msg;
}//End of toString() method
//Overrides accept method
void accept()
{
//Creates scanner class object
Scanner sc = new Scanner(System.in);
//Accepts data
System.out.println(" Name? ");
name = sc.nextLine();
System.out.println(" Age? ");
age = sc.nextInt();
sc.nextLine();
System.out.println(" City? ");
city = sc.nextLine();
System.out.println(" State? ");
state = sc.nextLine();
System.out.println(" Zip? ");
zip = sc.nextLine();
System.out.println(" Phone Number? ");
phoneNo = sc.nextLine();
}//End of accept method
//Overrides validate method
int validate()
{
int flag = 0;
try
{
//Checks name is null or not
if(name.length() == 0)
throw new NullPointerException();
}
catch(NullPointerException n)
{
System.out.println("Name cannot be left blank");
flag = 1;
}
try
{
//Checks age between 1 - 100
if(age <= 0)
throw new IllegalStateException();
if(age > 100)
throw new IllegalStateException();
}
catch(IllegalStateException ie)
{
System.out.println("Please enter a valid age from 1-100.  Age must be between 1 and
100");
flag = 1;
}
try
{
//Checks phone number must be exactly 12
if(phoneNo.length() != 12)
throw new IllegalStateException();
}
catch(IllegalStateException ie)
{
System.out.println("Please enter a phone number using the following format: ###-###-
####.  Phone number must be 12 character long");
flag = 1;
}
try
{
//Checks city must not be null
if(city.length() == 0)
throw new NullPointerException();
}
catch(NullPointerException n)
{
System.out.println("City cannot be left blank");
flag = 1;
}
try
{
//Checks state length must be exactly 2
if(state.length() != 2)
throw new IllegalStateException();
}
catch(IllegalStateException ie)
{
System.out.println("State must be exactly 2 characters");
flag = 1;
}
try
{
//Checks zip must be 5 character long
if(zip.length() != 5)
throw new IllegalStateException();
}
catch(IllegalStateException n)
{
System.out.println("Zip must be exactly 5 numeric characters");
flag = 1;
}
//returns the status flag
return flag;
}//End of method validate
}//End of class Personal Contact
//Driver class
public class ContactDemo
{
//Main method
public static void main(String ss[])
{
//Scanner class object created
Scanner sc = new Scanner(System.in);
//PersonalContact class object created
PersonalContact pc = new PersonalContact();
//BusinessContact class object created
BusinessContact bc = new BusinessContact();
//Loops till user enters 3
do
{
//Displays menu
System.out.println("1) Personal Contact");
System.out.println("2) Business Contact");
System.out.println("3) Exit ");
//Accepts user choice
int choice = sc.nextInt();
switch(choice)
{
case 1:
//Accepts personal contact
pc.accept();
//Calls the validate and checks the flag return value
//If it is zero then print personal contact
if(pc.validate() == 0)
System.out.println(pc);
break;
case 2:
//Accepts business contact
bc.accept();
//Calls the validate and checks the flag return value
//If it is zero then print business contact
if(bc.validate() == 0)
System.out.println(bc);
break;
case 3:
System.exit(0);
default:
System.out.println("Invalid Choice");
}//End of switch
}while(true);
}//End of main method
}//End of driver class
Output:
1) Personal Contact
2) Business Contact
3) Exit
1
Name?
Age?
101
City?
bam
State?
ori
Zip?
123
Phone Number?
12-23-45
Name cannot be left blank
Please enter a valid age from 1-100.
Age must be between 1 and 100
Please enter a phone number using the following format: ###-###-####.
Phone number must be 12 character long
State must be exactly 2 characters
Zip must be exactly 5 numeric characters
1) Personal Contact
2) Business Contact
3) Exit
2
Name?
Age?
0
Business Phone?
12-23-45
Cell Phone?
12-23-45
Name cannot be left blank
Please enter a valid age from 1-100.
Age must be between 1 and 100
Please enter a phone number using the following format: ###-###-####.
Phone number must be 12 character long
1) Personal Contact
2) Business Contact
3) Exit
1
Name?
Pyari
Age?
32
City?
Bam
State?
OR
Zip?
76000
Phone Number?
123-345-1234
Personal Contact: Pyari(32), Cell - 123-345-1234 City - Bam State - OR Zip - 76000
1) Personal Contact
2) Business Contact
3) Exit
2
Name?
Mohan
Age?
23
Business Phone?
123-456-6541
Cell Phone?
654-123-4567
Business Contact: Mohan(23), Business - 123-456-6541 Cell - 654-123-4567
1) Personal Contact
2) Business Contact
3) Exit
3

More Related Content

Similar to OverviewWe will be adding some validation to our Contact classes t.pdf

Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05CHOOSE
 
Technical aptitude Test 1 CSE
Technical aptitude Test 1 CSETechnical aptitude Test 1 CSE
Technical aptitude Test 1 CSESujata Regoti
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdffashionscollect
 
Presentation on design pattern software project lll
 Presentation on design pattern  software project lll  Presentation on design pattern  software project lll
Presentation on design pattern software project lll Uchiha Shahin
 
OXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART IOXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART IAbdul Rahman Sherzad
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsPVS-Studio
 
Make sure to make a copy of the Google Doc for this lab into.pdf
Make sure to make a copy of the Google Doc for this lab into.pdfMake sure to make a copy of the Google Doc for this lab into.pdf
Make sure to make a copy of the Google Doc for this lab into.pdfadityastores21
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type ScriptFolio3 Software
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Andrzej Jóźwiak
 
This project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdfThis project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdfjibinsh
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceAmrit Kaur
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScriptAleš Najmann
 
PT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docxPT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docxamrit47
 
FINAL PROJECTpacka.docx
FINAL PROJECTpacka.docxFINAL PROJECTpacka.docx
FINAL PROJECTpacka.docxAKHIL969626
 
Assignment Java Programming 2
Assignment Java Programming 2Assignment Java Programming 2
Assignment Java Programming 2Kaela Johnson
 

Similar to OverviewWe will be adding some validation to our Contact classes t.pdf (20)

Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
 
java
javajava
java
 
Technical aptitude Test 1 CSE
Technical aptitude Test 1 CSETechnical aptitude Test 1 CSE
Technical aptitude Test 1 CSE
 
Should be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdfShould be in JavaInterface Worker should extend Serializable from .pdf
Should be in JavaInterface Worker should extend Serializable from .pdf
 
Presentation on design pattern software project lll
 Presentation on design pattern  software project lll  Presentation on design pattern  software project lll
Presentation on design pattern software project lll
 
OXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART IOXUS20 JAVA Programming Questions and Answers PART I
OXUS20 JAVA Programming Questions and Answers PART I
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
 
Make sure to make a copy of the Google Doc for this lab into.pdf
Make sure to make a copy of the Google Doc for this lab into.pdfMake sure to make a copy of the Google Doc for this lab into.pdf
Make sure to make a copy of the Google Doc for this lab into.pdf
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
All You Need to Know About Type Script
All You Need to Know About Type ScriptAll You Need to Know About Type Script
All You Need to Know About Type Script
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
 
This project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdfThis project calls for the modification of the DollarFormat clas.pdf
This project calls for the modification of the DollarFormat clas.pdf
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
 
PT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docxPT1420 Decision Structures in Pseudocode and Visual Basic .docx
PT1420 Decision Structures in Pseudocode and Visual Basic .docx
 
FINAL PROJECTpacka.docx
FINAL PROJECTpacka.docxFINAL PROJECTpacka.docx
FINAL PROJECTpacka.docx
 
Assignment Java Programming 2
Assignment Java Programming 2Assignment Java Programming 2
Assignment Java Programming 2
 

More from fathimaoptical

Define a knowledge-based agent, and describe its major components. W.pdf
Define a knowledge-based agent, and describe its major components. W.pdfDefine a knowledge-based agent, and describe its major components. W.pdf
Define a knowledge-based agent, and describe its major components. W.pdffathimaoptical
 
Create a function mean comp that compares the mean value of the odd n.pdf
Create a function mean comp that compares the mean value of the odd n.pdfCreate a function mean comp that compares the mean value of the odd n.pdf
Create a function mean comp that compares the mean value of the odd n.pdffathimaoptical
 
Compare naive, effector, and memory T & B cells (survival time, Ig &.pdf
Compare naive, effector, and memory T & B cells (survival time, Ig &.pdfCompare naive, effector, and memory T & B cells (survival time, Ig &.pdf
Compare naive, effector, and memory T & B cells (survival time, Ig &.pdffathimaoptical
 
Consider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdf
Consider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdfConsider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdf
Consider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdffathimaoptical
 
Choose one of the evolutions of CIT and discuss how it may have made.pdf
Choose one of the evolutions of CIT and discuss how it may have made.pdfChoose one of the evolutions of CIT and discuss how it may have made.pdf
Choose one of the evolutions of CIT and discuss how it may have made.pdffathimaoptical
 
Write a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdfWrite a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdffathimaoptical
 
Without the effects of cyanobacteria or algae on lichen metabolism, .pdf
Without the effects of cyanobacteria or algae on lichen metabolism, .pdfWithout the effects of cyanobacteria or algae on lichen metabolism, .pdf
Without the effects of cyanobacteria or algae on lichen metabolism, .pdffathimaoptical
 
What is this image trying to tell you about the American West.pdf
What is this image trying to tell you about the American West.pdfWhat is this image trying to tell you about the American West.pdf
What is this image trying to tell you about the American West.pdffathimaoptical
 
What is the difference between a defined-benefit and a defined-contr.pdf
What is the difference between a defined-benefit and a defined-contr.pdfWhat is the difference between a defined-benefit and a defined-contr.pdf
What is the difference between a defined-benefit and a defined-contr.pdffathimaoptical
 
This is question about excel cuers.How would you use Financial Fun.pdf
This is question about excel cuers.How would you use Financial Fun.pdfThis is question about excel cuers.How would you use Financial Fun.pdf
This is question about excel cuers.How would you use Financial Fun.pdffathimaoptical
 
The surface area to volume ration is least improtant in thea. sink.pdf
The surface area to volume ration is least improtant in thea. sink.pdfThe surface area to volume ration is least improtant in thea. sink.pdf
The surface area to volume ration is least improtant in thea. sink.pdffathimaoptical
 
The Martian calendar has sixteen months instead of twelve. What is t.pdf
The Martian calendar has sixteen months instead of twelve. What is t.pdfThe Martian calendar has sixteen months instead of twelve. What is t.pdf
The Martian calendar has sixteen months instead of twelve. What is t.pdffathimaoptical
 
Baby names and birth weights”IntroductionBabies are weighed soon.pdf
Baby names and birth weights”IntroductionBabies are weighed soon.pdfBaby names and birth weights”IntroductionBabies are weighed soon.pdf
Baby names and birth weights”IntroductionBabies are weighed soon.pdffathimaoptical
 
Question How can I called this method in the main, and how can I .pdf
Question How can I called this method in the main, and how can I .pdfQuestion How can I called this method in the main, and how can I .pdf
Question How can I called this method in the main, and how can I .pdffathimaoptical
 
Question 1. List and describe three rules of natural justice, provid.pdf
Question 1. List and describe three rules of natural justice, provid.pdfQuestion 1. List and describe three rules of natural justice, provid.pdf
Question 1. List and describe three rules of natural justice, provid.pdffathimaoptical
 
Postal ClerkAssistant. Why do the five steps of the recruitment pro.pdf
Postal ClerkAssistant. Why do the five steps of the recruitment pro.pdfPostal ClerkAssistant. Why do the five steps of the recruitment pro.pdf
Postal ClerkAssistant. Why do the five steps of the recruitment pro.pdffathimaoptical
 
Negotiation - Porto (Porto case).note this is a case study so the.pdf
Negotiation - Porto (Porto case).note this is a case study so the.pdfNegotiation - Porto (Porto case).note this is a case study so the.pdf
Negotiation - Porto (Porto case).note this is a case study so the.pdffathimaoptical
 
need help with my computer science lab assignemnt. this assignment i.pdf
need help with my computer science lab assignemnt. this assignment i.pdfneed help with my computer science lab assignemnt. this assignment i.pdf
need help with my computer science lab assignemnt. this assignment i.pdffathimaoptical
 
Name a protein that contacts the insulin receptor inside the cell.pdf
Name a protein that contacts the insulin receptor inside the cell.pdfName a protein that contacts the insulin receptor inside the cell.pdf
Name a protein that contacts the insulin receptor inside the cell.pdffathimaoptical
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdffathimaoptical
 

More from fathimaoptical (20)

Define a knowledge-based agent, and describe its major components. W.pdf
Define a knowledge-based agent, and describe its major components. W.pdfDefine a knowledge-based agent, and describe its major components. W.pdf
Define a knowledge-based agent, and describe its major components. W.pdf
 
Create a function mean comp that compares the mean value of the odd n.pdf
Create a function mean comp that compares the mean value of the odd n.pdfCreate a function mean comp that compares the mean value of the odd n.pdf
Create a function mean comp that compares the mean value of the odd n.pdf
 
Compare naive, effector, and memory T & B cells (survival time, Ig &.pdf
Compare naive, effector, and memory T & B cells (survival time, Ig &.pdfCompare naive, effector, and memory T & B cells (survival time, Ig &.pdf
Compare naive, effector, and memory T & B cells (survival time, Ig &.pdf
 
Consider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdf
Consider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdfConsider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdf
Consider the titration of50.0 mL of 0.217 M hydrazoic acid (HN3, Ka=.pdf
 
Choose one of the evolutions of CIT and discuss how it may have made.pdf
Choose one of the evolutions of CIT and discuss how it may have made.pdfChoose one of the evolutions of CIT and discuss how it may have made.pdf
Choose one of the evolutions of CIT and discuss how it may have made.pdf
 
Write a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdfWrite a GUI application to simulate writing out a check. The value o.pdf
Write a GUI application to simulate writing out a check. The value o.pdf
 
Without the effects of cyanobacteria or algae on lichen metabolism, .pdf
Without the effects of cyanobacteria or algae on lichen metabolism, .pdfWithout the effects of cyanobacteria or algae on lichen metabolism, .pdf
Without the effects of cyanobacteria or algae on lichen metabolism, .pdf
 
What is this image trying to tell you about the American West.pdf
What is this image trying to tell you about the American West.pdfWhat is this image trying to tell you about the American West.pdf
What is this image trying to tell you about the American West.pdf
 
What is the difference between a defined-benefit and a defined-contr.pdf
What is the difference between a defined-benefit and a defined-contr.pdfWhat is the difference between a defined-benefit and a defined-contr.pdf
What is the difference between a defined-benefit and a defined-contr.pdf
 
This is question about excel cuers.How would you use Financial Fun.pdf
This is question about excel cuers.How would you use Financial Fun.pdfThis is question about excel cuers.How would you use Financial Fun.pdf
This is question about excel cuers.How would you use Financial Fun.pdf
 
The surface area to volume ration is least improtant in thea. sink.pdf
The surface area to volume ration is least improtant in thea. sink.pdfThe surface area to volume ration is least improtant in thea. sink.pdf
The surface area to volume ration is least improtant in thea. sink.pdf
 
The Martian calendar has sixteen months instead of twelve. What is t.pdf
The Martian calendar has sixteen months instead of twelve. What is t.pdfThe Martian calendar has sixteen months instead of twelve. What is t.pdf
The Martian calendar has sixteen months instead of twelve. What is t.pdf
 
Baby names and birth weights”IntroductionBabies are weighed soon.pdf
Baby names and birth weights”IntroductionBabies are weighed soon.pdfBaby names and birth weights”IntroductionBabies are weighed soon.pdf
Baby names and birth weights”IntroductionBabies are weighed soon.pdf
 
Question How can I called this method in the main, and how can I .pdf
Question How can I called this method in the main, and how can I .pdfQuestion How can I called this method in the main, and how can I .pdf
Question How can I called this method in the main, and how can I .pdf
 
Question 1. List and describe three rules of natural justice, provid.pdf
Question 1. List and describe three rules of natural justice, provid.pdfQuestion 1. List and describe three rules of natural justice, provid.pdf
Question 1. List and describe three rules of natural justice, provid.pdf
 
Postal ClerkAssistant. Why do the five steps of the recruitment pro.pdf
Postal ClerkAssistant. Why do the five steps of the recruitment pro.pdfPostal ClerkAssistant. Why do the five steps of the recruitment pro.pdf
Postal ClerkAssistant. Why do the five steps of the recruitment pro.pdf
 
Negotiation - Porto (Porto case).note this is a case study so the.pdf
Negotiation - Porto (Porto case).note this is a case study so the.pdfNegotiation - Porto (Porto case).note this is a case study so the.pdf
Negotiation - Porto (Porto case).note this is a case study so the.pdf
 
need help with my computer science lab assignemnt. this assignment i.pdf
need help with my computer science lab assignemnt. this assignment i.pdfneed help with my computer science lab assignemnt. this assignment i.pdf
need help with my computer science lab assignemnt. this assignment i.pdf
 
Name a protein that contacts the insulin receptor inside the cell.pdf
Name a protein that contacts the insulin receptor inside the cell.pdfName a protein that contacts the insulin receptor inside the cell.pdf
Name a protein that contacts the insulin receptor inside the cell.pdf
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdf
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

OverviewWe will be adding some validation to our Contact classes t.pdf

  • 1. Overview We will be adding some validation to our Contact classes to prevent bad values from being stored in the classes. We will also let the user create new contact objects. Contact Classes Copy your three contact classes from your last homework to a new project. Change your Contact class to an abstract class. This will prevent instantiation of Contact objects. Add an abstract method, public void validate(), to your Contact class. Validation Implement the validate() method in your BusinessContact class. If the name field is the empty string or null, then throw a NullPointerException. If the age field is not between 1-100, then throw an IllegalStateException If either of the phone number fields is not exactly 12 characters, then throw an IllegalStateException Implement the validate() method in your PersonalContact class. Validate name and age as described above If the address or city field is the empty string or null, then throw a NullPointerException. If the state field is not exactly 2 characters, then throw an IllegalStateException If the zip code field is not exactly 5 numeric characters, then throw an IllegalStateException Note: you should not have any try-catch blocks in your contact classes. Driver Program Create a driver program that allows a user to create a personal or business contact. Your program should prompt the user for a contact type: Create a new contact? 1. Personal 2. Business 2 It should then prompt the user for all details for that contact type: Name? Susie Grace Age? 39 Business Phone? 222-333-4444 Cell Phone? 555-666-7777 Call your validate() method to check for bad input and then print out the toString() of your new contact object. Name? Susie Grace Age? 39
  • 2. Business Phone? 222-333-4444 Cell Phone? 555-666-7777 Business Contact: Susie Grace (39), business - 222-333-4444, cell - 555-666-7777 Validating User Input Your driver program should have appropriate try-catch blocks to respond to bad user input. This includes NullPointerExceptions and IllegalStateExceptions. Each exception type should print an appropriate message to the console. For example: Name? Susie Grace Age? -10 Business Phone? 222-333-4444 Cell Phone? 555-666-7777 Please enter a valid age from 1-100 Another Example: Name? Susie Grace Age? 39 Business Phone? 2223334444 Cell Phone? 555-666-7777 Please enter a phone number using the following format: ###-###-####. Solution import java.lang.Exception; import java.util.*; //Abstract class Contact abstract class Contact { //Instance variable String name; int age; String phoneNo; //Default constructor to initialize instance variables Contact() { name = null; age = 0;
  • 3. phoneNo = null; }//End of constructor //Abstract method to validate abstract int validate(); //Abstract method to accept abstract void accept(); }//End of abstract class Contact //Class BusinessContact derived from abstract class Contact class BusinessContact extends Contact { //Instance variable String businessPhone; //Default constructor BusinessContact() { //Calls base class constructor super(); businessPhone = null; }//End of constructor //Overrides toString() method to display public String toString() { String msg; msg = "Business Contact: " + name + "(" + age + ")," + " Business - " + businessPhone + " Cell - " + phoneNo; return msg; }//End of toString() method //Overrides accept() method void accept() { //Creates a scanner class object Scanner sc = new Scanner(System.in);
  • 4. //Accepts data System.out.println(" Name? "); name = sc.nextLine(); System.out.println(" Age? "); age = sc.nextInt(); sc.nextLine(); System.out.println(" Business Phone? "); businessPhone = sc.nextLine(); System.out.println(" Cell Phone? "); phoneNo = sc.nextLine(); }//End of accept method //Overrides validate method int validate() { int flag = 0; try { //Checks if name is zero length if(name.length() == 0) throw new NullPointerException(); } catch(NullPointerException n) { System.out.println("Name cannot be left blank"); //Sets the flag to 1 flag = 1; } try { //Checks age for between 1 - 100 if(age <= 0) throw new IllegalStateException(); if(age > 100) throw new IllegalStateException(); }
  • 5. catch(IllegalStateException ie) { System.out.println("Please enter a valid age from 1-100. Age must be between 1 and 100"); flag = 1; } try { //Checks phone number length for exactly 12 if(phoneNo.length() != 12) throw new IllegalStateException(); } catch(IllegalStateException ie) { System.out.println("Please enter a phone number using the following format: ###-###- ####. Phone number must be 12 character long"); flag = 1; } //returns the flag status return flag; }//End of method validate }//End of class Business contact //class PersonalContact derived from abstract class Contact class PersonalContact extends Contact { //Instance variable String city, state, zip; //Default constructor PersonalContact() { //Calls the base class constructor super(); city = null; state = null; zip = null;
  • 6. }//End of constructor //Overrides toString() method to display public String toString() { String msg; msg = "Personal Contact: " + name + "(" + age + ")," + " Cell - " + phoneNo + " City - " + city + " State - " + state + " Zip - " + zip; return msg; }//End of toString() method //Overrides accept method void accept() { //Creates scanner class object Scanner sc = new Scanner(System.in); //Accepts data System.out.println(" Name? "); name = sc.nextLine(); System.out.println(" Age? "); age = sc.nextInt(); sc.nextLine(); System.out.println(" City? "); city = sc.nextLine(); System.out.println(" State? "); state = sc.nextLine(); System.out.println(" Zip? "); zip = sc.nextLine(); System.out.println(" Phone Number? "); phoneNo = sc.nextLine(); }//End of accept method //Overrides validate method int validate() {
  • 7. int flag = 0; try { //Checks name is null or not if(name.length() == 0) throw new NullPointerException(); } catch(NullPointerException n) { System.out.println("Name cannot be left blank"); flag = 1; } try { //Checks age between 1 - 100 if(age <= 0) throw new IllegalStateException(); if(age > 100) throw new IllegalStateException(); } catch(IllegalStateException ie) { System.out.println("Please enter a valid age from 1-100. Age must be between 1 and 100"); flag = 1; } try { //Checks phone number must be exactly 12 if(phoneNo.length() != 12) throw new IllegalStateException(); } catch(IllegalStateException ie) { System.out.println("Please enter a phone number using the following format: ###-###- ####. Phone number must be 12 character long");
  • 8. flag = 1; } try { //Checks city must not be null if(city.length() == 0) throw new NullPointerException(); } catch(NullPointerException n) { System.out.println("City cannot be left blank"); flag = 1; } try { //Checks state length must be exactly 2 if(state.length() != 2) throw new IllegalStateException(); } catch(IllegalStateException ie) { System.out.println("State must be exactly 2 characters"); flag = 1; } try { //Checks zip must be 5 character long if(zip.length() != 5) throw new IllegalStateException(); } catch(IllegalStateException n) { System.out.println("Zip must be exactly 5 numeric characters"); flag = 1; } //returns the status flag
  • 9. return flag; }//End of method validate }//End of class Personal Contact //Driver class public class ContactDemo { //Main method public static void main(String ss[]) { //Scanner class object created Scanner sc = new Scanner(System.in); //PersonalContact class object created PersonalContact pc = new PersonalContact(); //BusinessContact class object created BusinessContact bc = new BusinessContact(); //Loops till user enters 3 do { //Displays menu System.out.println("1) Personal Contact"); System.out.println("2) Business Contact"); System.out.println("3) Exit "); //Accepts user choice int choice = sc.nextInt(); switch(choice) { case 1: //Accepts personal contact pc.accept(); //Calls the validate and checks the flag return value //If it is zero then print personal contact if(pc.validate() == 0) System.out.println(pc); break; case 2:
  • 10. //Accepts business contact bc.accept(); //Calls the validate and checks the flag return value //If it is zero then print business contact if(bc.validate() == 0) System.out.println(bc); break; case 3: System.exit(0); default: System.out.println("Invalid Choice"); }//End of switch }while(true); }//End of main method }//End of driver class Output: 1) Personal Contact 2) Business Contact 3) Exit 1 Name? Age? 101 City? bam State? ori Zip? 123 Phone Number? 12-23-45 Name cannot be left blank Please enter a valid age from 1-100. Age must be between 1 and 100 Please enter a phone number using the following format: ###-###-####.
  • 11. Phone number must be 12 character long State must be exactly 2 characters Zip must be exactly 5 numeric characters 1) Personal Contact 2) Business Contact 3) Exit 2 Name? Age? 0 Business Phone? 12-23-45 Cell Phone? 12-23-45 Name cannot be left blank Please enter a valid age from 1-100. Age must be between 1 and 100 Please enter a phone number using the following format: ###-###-####. Phone number must be 12 character long 1) Personal Contact 2) Business Contact 3) Exit 1 Name? Pyari Age? 32 City? Bam State? OR Zip? 76000 Phone Number? 123-345-1234
  • 12. Personal Contact: Pyari(32), Cell - 123-345-1234 City - Bam State - OR Zip - 76000 1) Personal Contact 2) Business Contact 3) Exit 2 Name? Mohan Age? 23 Business Phone? 123-456-6541 Cell Phone? 654-123-4567 Business Contact: Mohan(23), Business - 123-456-6541 Cell - 654-123-4567 1) Personal Contact 2) Business Contact 3) Exit 3