Access data to set method by constructors - java

I'm using Java and my code is BUILD SUCCESSFUL, but I don't get result I want. I'm tring to pass data input from user in main class to another class called Staff. I guess during runtime my data never pass through set and get methods to checked. How can I make them work?
Main class
System.out.print("please enter staff ID: ");
String staffID = in.next();
System.out.println("please enter staff first name and last name:");
String Fname = in.next();
String Lname = in.next();
Staff staff= new Staff (staffID, Fname, Lname);
System.out.print(staff.toString());
Staff Class
public class Staff {
private String StaffID;
private String Fname;
private String Lname;
Staff (String StaffID, String Fname, String Lname){
this.StaffID = StaffID;
this.Fname = Fname;
this.Lname = Lname;
}
//set & get Staff ID
public void setStaffID (String StaffID){
if (this.StaffID.length() <= 7) {
this.StaffID = StaffID;
}
else
System.out.println("ID have to be less than or equal 7 digits");
}
public String getStaffID (){
return this.StaffID;
}
//set & get First name
public void setFname(String Fname){
if (Fname.matches("[a-zA-Z]")){
this.Fname =Fname;
}
else
System.out.print("Name have to contains letters only");
}
public String getFname(){
return this.Fname;
}
//set & get Last name
public void setLname(String Lname){
if (Fname.matches("[a-zA-Z]")){
this.Lname =Lname;
}
else
System.out.print("Name have to contains letters only");
}
public String getLname(){
return this.Lname;
}
#Override
public String toString(){
return "\n\t\tStaff information \nID: " + this.StaffID + "\nFirst name: " + this.Fname
+"\nLast name: " +this.Lname ;
}

You need to change your constructor to use the setters like
Staff (String StaffID, String Fname, String Lname){
setStaffID(StaffID);
setFname(Fname);
setLname(Lname);
}

Related

Create a class Student with following attributes

I'm trying to learn the array object in Java but don't understand. I did understand how to store input into an array object but fail to understand how to compare each items inside an array to do #7 and #8. I tried to search up on the internet but stuck from there.
Create a class Student with following attributes: Name, Age, Address, Email address
Create an empty constructor that initializes empty values to all the attributes.
Create a constructor that takes all the parameters and initializes all the attributes with it.
Create accessor and mutator methods for all attributes.
Create a toString method to return the details of the student.
Ask the user to enter the details of any 5 students and store them in an array.
Ask the user to enter an address and print all the students who live in that address.
Print all the students whose email address contains “gmail.com”.
import java.util.*;
public class Student{
private String name;
private int age;
private String address;
private String email;
public Student(){}
public Student(String name, int age, String address, String email){
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
public void setName(String newName){
name = newName;
}
public void setAge(int newAge){
age = newAge;
}
public void setAddress(String newAddress){
address = newAddress;
}
public void setEmail(String newEmail){
email = newEmail;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String getAddress(){
return address;
}
public String getEmail(){
return email;
}
public String toString() {
return "Name: " + name + ", Age: " + age + ", Address: " + address + ", Email: " + email;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Student[] s= new Student[];5
for(int i = 0; i < 5; i++){
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Age: ");
int age = sc.nextInt();
System.out.print("Address: ");
sc.nextLine();
String address = sc.nextLine();
System.out.print("Email: ");
String email = sc.nextLine();
s[i] = new Student(name,age,address,email);
}
for(int i = 0; i < s.size(); i++){
if(s)
}
System.out.println(Arrays.toString(s));
}
}
For 7, use the scanner to retrieve a string from the user, then compare it to each user's address
System.out.print("Please enter an address: ");
String anyAddress = sc.nextLine();
for (int i = 0; i < s.length; i++) {
if (s[i].getAddress().equals(anyAddress))
System.out.println(s[i]);
}
For 8, it's quite the same, iterate on the student (I show there a for-each loop), then verify if "gmail.com"is in their email, if true, then print it
for (Student student : s) {
if (student.getEmail().contains("gmail.com"))
System.out.println(student);
}

java.lang.NoSuchMethodException: Practice.Virual.main [class [Ljava.lang.String;] at java.lang.Class.getMethod(Class.java:2072) a error

What's wrong with my code? I'm new to coding so i may got something wrog here even though my code runs.. there's seem to be nothing run with my code though. the error that was showing was paste at the bottom of this post.
String name, streetname, barangay, city, region;
int zipcode, streetno;
void display() {
System.out.println("Name: " + this.name);
System.out.println("Street No: " + this.streetno);
System.out.println("Street: " + this.streetname);
System.out.println("Barangay: " + this.barangay);
System.out.println("City : " + this.city);
System.out.println("Region: " + this.region);
System.out.println("Zip Code : " + this.zipcode);
}
}
class residentinfo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Virual rsd = new Virual();
System.out.println("Enter Name: ");
rsd.name = in.nextLine();
System.out.println("Enter Street No: ");
rsd.streetno = in.nextInt();
System.out.println("Enter Street Name: ");
rsd.streetname = in.nextLine();
System.out.println("Enter Barangay: ");
rsd.barangay = in.nextLine();
System.out.println("Enter City: ");
rsd.city = in.nextLine();
System.out.println("Enter Region: ");
rsd.region = in.nextLine();
System.out.println("Enter Zip Code: ");
rsd.zipcode = in.nextInt();
rsd.display();
}
}
What's wrong with my code? When i run it this error showed up. there's seem to be nothing run with my code, and it runs already.
java.lang.NoSuchMethodException: Practice.Virual.main [class [Ljava.lang.String;] at java.lang.Class.getMethod(Class.java:2072)
at java.lang.Class.getDeclaredMethod(Class.java:2050)
at com.duy.android.compiler.java.Java.run(Java.java:105)
at com.duy.ide.javaide.run.activities.ExecuteActivity.executeDex(ExecuteActivity.java:147)
at com.duy.ide.javaide.run.activities.ExecuteActivity.exec(ExecuteActivity.java:124)
at com.duy.ide.javaide.run.activities.ExecuteActivity.access$100(ExecuteActivity.java:45)
at com.duy.ide.javaide.run.activities.ExecuteActivity$1.run(ExecuteActivity.java:88)
at java.lang.Thread.run(Thread.java:923
There is a several things which you should fix with your code.
In general class names start with upper case letters in Java.
And you should use getter and setters for you variables for best practice. Also you can't read streetName with your current code because when you call in.nextInt() method it doesn't consume new line character. And also for best practice you should use camelCase for you variable names.
Here is a better aproach to your code.
public class Virual {
private String name;
private String streetName;
private String barangay;
private String city;
private String region;
private int zipcode;
private int streetNo;
public Virual() {
}
#Override
public String toString() {
return String.format("Name: %s Street No: %d Street: %s Barangay: %s City : %s Region: %s Zip Code : %d", name, streetNo, streetName, barangay, city, region, zipcode);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getBarangay() {
return barangay;
}
public void setBarangay(String barangay) {
this.barangay = barangay;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public int getStreetNo() {
return streetNo;
}
public void setStreetNo(int streetNo) {
this.streetNo = streetNo;
}
}
public class ResidentInfo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Virual rsd = new Virual();
System.out.println("Enter Name: ");
rsd.setName(in.nextLine());
System.out.println("Enter Street No: ");
rsd.setStreetNo(in.nextInt());
in.nextLine(); //to consume /n character (new line)
/*if you don't put in.nextLine after in.nextInt , in.nextInt method don't read newline char
so you can't enter value for street name
*/
System.out.println("Enter Street Name: ");
rsd.setStreetName(in.nextLine());
System.out.println("Enter Barangay: ");
rsd.setBarangay(in.nextLine());
System.out.println("Enter City: ");
rsd.setCity(in.nextLine());
System.out.println("Enter Region: ");
rsd.setRegion(in.nextLine());
System.out.println("Enter Zip Code: ");
rsd.setZipcode(in.nextInt());
System.out.println(rsd.toString());
}
}

Java Enrollment register

I have to write a program using java to store and manage a set of students enrolled on a course.
For each student, their name, date of birth (dd/mm/yyyy),address and gender should be stored.
The program needs to enable students to be added to the course or deleted from the course. And the program user must be able to search for a student by name (Assuming the name is unique).
This is what I have so far:
import java.util.Scanner;
public class Student {
private String name;
private String address;
private String gender;
private String dob;
Scanner in = new Scanner(System.in);
public Student(String sName, String sAddress, String sGender, String sDob) {
name = sName;
address = sAddress;
gender = sGender;
dob = sDob;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getGender() {
return gender;
}
public String getDob() {
return dob;
}
public void setName(String name) {
System.out.println("Please enter the students name");
name = in.nextLine();
}
public void setAddress(String address) {
System.out.println("Please enter the students address");
address = in.nextLine();
}
public void setGender(String gender) {
System.out.println("Please enter the students gender");
gender = in.nextLine();
}
public void setDob(String dob) {
System.out.println("Please enter the students DOB");
dob = in.nextLine();
}
}
public class student_tester {
public static void main (String [] args) {
Student student01 = new Student ("", "" ,"", "");
student01.setName(null);
student01.setAddress(null);
student01.setGender(null);
student01.setDob(null);
Student student02 = new Student ("", "" ,"", "");
student02.setName(null);
student02.setAddress(null);
student02.setGender(null);
student02.setDob(null);
}
}
A good practice is to Maintain a unique identifier field such as Student ID in the Student class. You can maintain a List in your driver program i.e student tester with the main method .
Make sure you read the input in your tester class or driver class and not in student class. So you can keep adding each student object to the list.
import java.util.Scanner;
public class student_tester {
public static void main (String [] args) {
List<Student> allStudents =new ArrayList<Student>();
Scanner in = new Scanner(System.in);
while(true){
Student student01 = new Student ();
System.out.println("Please enter the students name");
student01.setName(in.nextLine());
System.out.println("Please enter the students address");
student01.setAddress(in.nextLine());
System.out.println("Please enter the students DOB");
student01.setDob(in.nextLine());
System.out.println("Please enter the students gender");
student01.setGender(in.nextLine());
}
}
you should read input in the tester class and loop through to keep adding new students as the user inputs.
For search on the basis of a field :
eg Search and delete on giving a student's name.
public Student search( String studentName){
foreach(Student s : allStudents)
if(s.getName().equals(studentName){
// you can return this student object or print his other details
// System.out.println(s.getAddress()); etc
return s;
}
return null;
}
}
for delete :
public void delete(String studentName)
foreach(Student s : allStudents)
if(s.getName().equals(studentName){
allStudents.remove(s);
}
}
}
You can remove the constructor with 4 paramters in the Student class. And change all the setters as per:
;
public class Student {
// private String id .. maybe
private String name;
private String address;
private String gender;
private String dob;
//for clarity
public Student(){
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getGender() {
return gender;
}
public String getDob() {
return dob;
}
public void setName(String name) {
this.name=name;
}
public void setAddress(String address) {
this.address=address;
}
public void setGender(String gender) {
this.gender=gender;
}
public void setDob(String dob) {
this.dob=dob;
}
}

Trying to get my arraylist to print a given item

I'm trying to get a contact list created in Java. I think I have most of it, though I'm sure it could be enhanced. I believe I can add items to the arraylist, however, when I try to print the arraylist I'm getting some random text and numbers. Also, I'm not kind of lost on identifying by a contact id number and then just printing that contact. Any help or reference to material would help a lot! I've tried going through text books and researching online, and to be honest, now I'm just more confused. Here's my code:
Main:
package contactslist;
import java.util.*;
import java.io.*;
public class ContactsList {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
int type = 0;
ArrayList<Contacts> contacts = new ArrayList<Contacts>();
while(type != 4){
System.out.println("[1] Personal Contact");
System.out.println("[2] Business Contact");
System.out.println("[3] Display Contacts");
System.out.println("[4] to quit");
type = input1.nextInt();
if(type == 4){
System.out.println("Goodbye");
break;
}
else if (type == 3){
int totalContacts = contacts.size();
for (int i = 0; i < totalContacts; i++){
System.out.print(contacts);
}
}
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter a numeric ContactId: ");
String contactId = inputs.nextLine();
System.out.println("Please enter First Name: ");
String firstName = inputs.nextLine();
if (firstName == null) {
break;
}
System.out.println("Please enter Last Name: ");
String lastName = inputs.nextLine();
if (lastName == null) {
break;
}
System.out.println("Please enter Address: ");
String address = inputs.nextLine();
System.out.println("Please enter Phone Number: ");
String phoneNumber = inputs.nextLine();
System.out.println("Please enter Email Address: ");
String emailAddress = inputs.nextLine();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = inputs.nextLine();
Contacts personal = new PersonalContact(contactId, firstName, lastName, address,
phoneNumber, emailAddress, dateofBirth);
contacts.add(personal);
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = inputs.nextLine();
System.out.println("Please enter Organization: ");
String organization = inputs.nextLine();
Contacts business = new BusinessContact(contactId, firstName, lastName,
address, phoneNumber, emailAddress, jobTitle, organization);
contacts.add(business);
}
}
}
}
Contacts Class:
package contactslist;
import java.util.*;
import java.io.*;
public abstract class Contacts {
String contactId;
String firstName;
String lastName;
String address;
String phoneNumber;
String emailAddress;
public Contacts(String contactId,String firstName,String lastName, String address,
String phoneNumber, String emailAddress)
{
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}
public void setContactId(String input){
this.contactId = input;
}
public String getContactId(){
return contactId;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getLastName(){
return lastName;
}
public void setAddress(String input){
this.address = input;
}
public String getAddress(){
return address;
}
public void setPhoneNumber(String input){
this.phoneNumber = input;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setEmailAddress(String input){
this.emailAddress = input;
}
public String getEmailAddress(){
return emailAddress;
}
public void displayContacts(){
System.out.println("Contact ID: " + contactId + " First Name: " + firstName + "
Last Name: " + lastName);
}
}
Personal Subclass:
package contactslist;
import java.util.*;
import java.io.*;
public class PersonalContact extends Contacts{
private String dateofBirth;
public PersonalContact(String contactId, String firstName, String lastName, String
address, String phoneNumber, String emailAddress, String dateofBirth){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.dateofBirth = dateofBirth;
}
public void setDateofBirth(String input){
this.dateofBirth=input;
}
public String getDateofBirth(){
return this.dateofBirth;
}
#Override
public void displayContacts(){
System.out.print("Personal Contacts: ");
System.out.println("Contact ID: " + contactId + " First Name: " + firstName + " Last
Name: " + lastName);
System.out.println("Address: " + address);
System.out.println("Phone Number: " + phoneNumber);
System.out.println("Email Address: " + emailAddress);
System.out.println("Birthday: " + dateofBirth);
}
}
Business Subclass:
package contactslist;
public class BusinessContact extends Contacts{
private String jobTitle;
private String organization;
public BusinessContact(String contactId, String firstName, String lastName, String
address, String phoneNumber, String emailAddress, String jobTitle, String organization)
{
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.jobTitle = jobTitle;
this.organization = organization;
}
public void jobTitle(String input){
this.jobTitle = jobTitle;
}
public String getjobTitle(){
return this.jobTitle;
}
public void organization(String input) {
this.organization = organization;
}
public String getOrganization(){
return this.organization;
}
#Override
public void displayContacts(){
System.out.print("Personal Contacts: ");
System.out.println("First Name: " + firstName + " Last Name :" + lastName);
System.out.println("Address: " + address);
System.out.println("Phone Number: " + phoneNumber);
System.out.println("Email Address: " + emailAddress);
System.out.println("Job Title: " + jobTitle);
System.out.println("Orgnanization: " + organization);
}
}
And here's what prints when I choose option 3, to display the contacts.
Error:
[contactslist.PersonalContact#1df38fd]
Any help would be greatly appreciated. I'm going crazy, and please forgive me for the question. I've tried a few different things that I've googled, and I'm just not getting it. Can someone point me in the right direction, or give me a good site to reference?
You need to code your own method to print that ArrayList. Something like :
public void printAllContacts(ArrayList<Contacts> contacts) {
for (Contacts c : contacts) {
c.displayContacts();
}
}
and call that instead of System.out.println(contacts); (Java will only print information about that object) for option 3.
Read more about ArrayList here : https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

How to add valid input into arraylist?

This is my ID program which stores first name, last name, date and place on birth, email and phone number. How do I make and store a person object with only valid birth date, email and phone number (instead of having all the attributes)?
This is my main ID program:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ID {
static List<Oseba> id = new ArrayList<Oseba>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
int choice = 0;
boolean isDate = false;
String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
System.out.println("How many IDs would you like to enter? ");
max = sc.nextInt();
System.out.println(" 0. Exit. ");
System.out.println(" 1. Add contact. ");
System.out.println(" 2. Outprint all contacts. ");
choice = sc.nextInt();
while (choice != 0) {
switch (choice) {
case 0:
System.out.println("Goodbye!");
System.exit(0);
case 1:
while (choice != 2) {
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter date of birth (dd-mm-yyyy): ");
String date = sc.next();
isDate = date.matches(regEx_Date);
System.out.println("Enter place of birth: ");
String place = sc.next();
System.out.println("Enter email: ");
String email = sc.next();
Pattern p = Pattern.compile(regEx_Email);
Matcher m = p.matcher(email);
if (m.find()) {
System.out.println(email + " is a valid email address.");
} else {
System.out.println(email + " is a invalid email address");
}
System.out.println("Enter phone number:");
String phone = sc.next();
addID(firstName, lastName, date, place, email, phone);
}
break;
case 2:
System.out.println("\n" + ID.id);
break;
default:
System.out.println("Try again.");
break;
}
System.out.println(" 0. Exit. ");
System.out.println(" 1. Add contact. ");
System.out.println(" 2. Outprint all contacts. ");
choice = sc.nextInt();
}
}
private static void addID(String firstName, String lastName, String date, String place, String email, String phone) {
Person p = new Person(firstName, lastName, date, place, email, phone);
id.add(p);
}
}
And my Person class:
class Person {
String firstName;
String lastName;
String date;
String place;
String email;
String phone;
public Person(String firstName, String lastName, String date, String place, String email, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.date = date;
this.place = place;
this.email = email;
this.phone = phone;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String toString() {
return "First Name: " + firstName + "\n"
+ "Last Name: " + lastName + "\n"
+ "Date of birth: " + date + "\n"
+ "Place of birth: " + place + "\n"
+ "Email: " + email + "\n"
+ "Phone number: " + phone + "\n\n";
}
}
Thanks for the help.
The best approach would be to break down your problem into smaller ones. For example, in order to validate the input, what you will have to do, instead of calling the setter directly is to create a method that will be responsible to validate the input for every single case. Try to use this approach everywhere since low coupling and high cohesion is always a requirement! I will provide an example on your implementation, however, there are multiple ways to do that. Also I wont use exceptions since I noticed that you are still in the beginning.
Apart from that, in order for this to work, you should add a default constructor(the values are predifined) in the Person Class.
Finally, eventhough the approach with multiple while loops is not recommented because it makes the code more complicated, I used it in order to demonstrate you how you can make sure that you will get the correct input, for example if the user input doesnt get validated, then the program will continue to ask the user until it will get the correct input. Additionally, when the user makes a mistake, directions should be provided in order to guide him/her. (this is normally done with exceptions, in our case though we provide this with simple console prints).
So let's see:
public class ID {
static List<Oseba> id = new ArrayList<Oseba>();
\*we create the menu like that in order to avoid multiple lines repetitions *\
private static String menuOptions = "Menu:" + "\nExit - Insert 0"
+ "\nAdd contact - Insert 1" + "\nExit Outprint all contacts - Insert 2";
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0;
int choice = 0;
boolean isDate = false;
System.out.println("How many IDs would you like to enter? ");
max = sc.nextInt();
Person p = new Person();
while (true) {
print(menuOptions);
choice = sc.nextInt();
switch (choice) {
case 0:
System.out.println("Goodbye!");
System.exit(0);
case 1:
while(true){
String fname = getString("Enter First Name: ");
if(verifyName(fname)){
p.setFirstName(fname);
break;
}
}
while(true){
String lname = getString("Enter Last Name: ");
if(verifyName(lname)){
p.setLastName(lname);
break;
}
}
while(true){
String date = getString("Enter date of birth (dd-mm-yyyy): ");
if(verifyBirthDate(date)){
p.setDate(date);
break;
}
}
while(true){
String birthPlace = getString("Enter place of birth: ");
if(verifyBirthPlace(birthPlace)){
p.setPlace(birthPlace);
break;
}
}
while(true){
String email = getString("Enter email address: ");
if(verifyEmail(email)){
p.setEmail(email);
break;
}
}
while(true){
String phoneNumber = getString("Enter phone number: ");
if(verifyPhoneNumber(phoneNumber)){
p.setPhone(phoneNumber);
break;
}
}
addID(p);
break;
case 2:
System.out.println("\n" + ID.id);
break;
default:
System.out.println("Try again.");
break;
}
print(menuOptions);
choice = sc.nextInt();
}
}
private static void addID(Person prs) {
id.add(prs);
}
public static Boolean verifyName(String name) {
if(!name.matches("[a-zA-Z]+")){
print("\nERROR_MESSAGE:____________The first/last name should contain only letters, everything else is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyBirthDate(String date) {
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
if(!date.matches(regEx_Date)){
print("\nERROR_MESSAGE:____________The birth date is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyBirthPlace(String birthPlace) {
if(!birthPlace.matches("[a-zA-Z]+")){
print("\nERROR_MESSAGE:____________The birth place is not valid!");
return false;
}else{
return true;
}
}
public static Boolean verifyEmail(String email) {
String regEx_Email = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern p = Pattern.compile(regEx_Email);
Matcher m = p.matcher(email);
if(!m.find()){
print("\nERROR_MESSAGE:____________"+email+" is an invalid email address");
return false;
}else{
return true;
}
}
public static Boolean verifyPhoneNumber(String phoneNumber) {
if(!phoneNumber.matches("[0-9]+")){
print("\nERROR_MESSAGE:____________The phone No. should contain only numbers, everything else is not valid!");
return false;
}else{
return true;
}
}
public static String getString(String msg) {
Scanner in = new Scanner(System.in);
print(msg);
String s = in.nextLine();
return s;
}
public static void print(String s) {
System.out.println(s);
}
}
Create a constructor like this
public Person(String date, String email, String phone) {
this.date = date;
this.email = email;
this.phone = phone;
}
You could optionally add
this.firstName = null;
this.lastName = null;
//for all of your fields.
You also need to uodate your getters and toString method to check if the field has been initialized. For example, for your getFirstName()
if (firstName!=null)
return firstName;
return "";
May better name for isDate field is isValidDate.
Can you use simple if statement:
if(isValidDate && m.find())
addID(firstName, lastName, date, place, email, phone);
Or can you create method for checking validation:
private boolean isValidDate(String date){
if(number!=null && number!=""){
String regEx_Date = "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
return date.matches(regEx_Date);
}
return false;
}
Have you ever heard about Primitive Obsession?
I would use a Date (JodaDate) instead of String for birth date.
I would create an Email value object, throwing an IllegalArgumentException if the String provided isn't a valid email (validated by regexp).
I would create a Phone value object, throwing an IllegalArgumentException if the String provided isn't a valid phone number.
The constructor becoming:
public Person(String firstName, String lastName, Date birthDate, String place, Email email, Phone phone)
For instance, the Email object would be:
public class Email {
private String value;
public Email(String email) {
if(isNotValid(email))
throw new IllegalArgumentException("Your mail is not valid!");
this.value = email;
}
public final String getValue(){
return email;
}
private boolean isNotValid(){
//return false if email regexp validation is not verified
}
//....equals - hashcode if needed here
}
Thus, your Person would always be a valid person.
Indeed, checking that its components are valid is then the responsibility of the client, not the Person directly. It's more informative for the reader what a Person expects, just by reading the API.
Add a new boolean variable to keep track valid inputs. If all inputs are valid then only add Person object to ArrayList
boolean isValid=true;
if (m.find()) {
System.out.println(email + " is a valid email address.");
} else {
isValid=false;
System.out.println(email + " is a invalid email address");
}
if(isValid)
{
//Do other check phone number and valid birth date similarly
}
if(isValid)
{
addID(firstName, lastName, date, place, email, phone);
}

Categories

Resources