SlideShare a Scribd company logo
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-05
CHOOSE
 
java
javajava
Technical aptitude Test 1 CSE
Technical aptitude Test 1 CSETechnical aptitude Test 1 CSE
Technical aptitude Test 1 CSE
Sujata 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 .pdf
fashionscollect
 
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 I
Abdul Rahman Sherzad
 
Analysis of Microsoft Code Contracts
Analysis of Microsoft Code ContractsAnalysis of Microsoft Code Contracts
Analysis of Microsoft Code Contracts
PVS-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.pdf
adityastores21
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
Ajenkris Kungkung
 
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
Folio3 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 2020
Andrzej Jóźwiak
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
Vikram Nandini
 
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
jibinsh
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin 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 TypeScript
Aleš 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 .docx
amrit47
 
FINAL PROJECTpacka.docx
FINAL PROJECTpacka.docxFINAL PROJECTpacka.docx
FINAL PROJECTpacka.docx
AKHIL969626
 
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiM2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
rakshithatan
 

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
 
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiM2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
 

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.pdf
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 
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
fathimaoptical
 

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

Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
EduSkills OECD
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 

Recently uploaded (20)

Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Francesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptxFrancesca Gottschalk - How can education support child empowerment.pptx
Francesca Gottschalk - How can education support child empowerment.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 

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