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
Related
I have an object user from a constructor customer and I want to add this object to the HashMap, but I don't have the values for user because it's input. After I added it to HashMap how can I check if this particular user is already in the HashMap or not?
UsersList is the name of the HashMap. Here is my code:
import java.util.HashMap;
import java.util.Scanner;
public class Customer {
int id;
String Name;
String email;
String mobile;
String password;
String city;
String postcode;
public static String input;
Scanner scanner = new Scanner(System.in);
Customer user = new Customer();
Customer() {
}
Customer(int id, String Name, String city, String postcode, String email, String mobile, String password) {
this.id = id;
this.Name = Name;
this.city = city;
this.postcode = postcode;
this.email = email;
this.mobile = mobile;
this.password = password;
}
public String getName() {
return Name;
}
public void setName(String name) {
System.out.println ("Enter your name:");
String Name = scanner.nextLine();
this.Name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
System.out.println("Enter your email:");
user.email = scanner.nextLine();
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
System.out.println("Enter your mobile number:");
user.mobile = scanner.nextLine();
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
System.out.println("Enter your password:");
user.password = scanner.nextLine();
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getcity() {
return city;
}
public void setcity(String city) {
System.out.println("Enter your city:");
user.city = scanner.nextLine();
this.city = city;
}
public String getpostcode() {
return postcode;
}
public void setpostcode(String postcode) {
System.out.println("Enter postcode:");
user.postcode = scanner.nextLine();
this.postcode = postcode;
}
public void main(String[] args) {
do {
System.out.println("Enter \"login\", \"register\", or \"exit\"");
input = scanner.nextLine();
if (input.equals("login")) {
// get login details
user.setName(user.Name);
user.setPassword(user.password);
System.out.printf("%s login");
} else if (input.equals("register")) {
// get register details
user.setName(user.Name);
user.setMobile(user.mobile);
user.setPassword(user.password);
user.setEmail(user.email);
user.setcity(user.city);
user.setpostcode(user.postcode);
HashMap<String, Customer> UsersList = new HashMap<>();
UsersList.put("user", new Customer(id, Name, city, postcode, email, mobile, password));
// Customer testCustomer = UsersList.get("user");
// int id= testCustomer.getId();
if (UsersList.containsValue(id)) {
System.out.printf("your account is already registered \n");
}
// String email= testCustomer.getEmail();
else {
System.out.printf("you create your account succefully \n");
System.out.printf("Enter 'login' to log in or 'register' to open another account");
input = scanner.nextLine();
}
} else if (input.equals("exit")) {
break; // exit the loop
} else {
System.out.printf("invalid input , try again");
input = scanner.nextLine();
// invalid input
}
} while (true);
}
}
This is probably what you are looking for right now:
import java.util.*;
class Customer {
String name, email, mobile, password, city, postcode;
Customer(){}
Customer (String name, String email, String mobile, String city, String postcode, String password)
{
this.name = name;
this.city = city;
this.postcode = postcode;
this.email = email;
this.mobile = mobile;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getpostcode() {
return postcode;
}
public void setpostcode(String postcode) {
this.postcode = postcode;
}
public String toString() {
return this.name + " " + this.email + " " + this.mobile + " " + this.city + " " + this.postcode;
}
public void print() {
System.out.println(this.name + " " + this.email + " " + this.mobile + " " + this.city + " " + this.postcode);
}
public static void main(String[] args) {
Customer user = new Customer();
Scanner sc = new Scanner(System.in);
HashMap<String, String> hm = new HashMap<>();
while (true) {
System.out.println("\n\nChoose (1,2,3): \n1) Login \n2) Register \n3) Exit");
int input = sc.nextInt();
switch (input) {
// get login details
case 1:
Scanner login = new Scanner(System.in);
System.out.print("Enter name: ");
user.setName(login.nextLine());
System.out.print("Enter password: ");
user.setPassword(login.nextLine());
System.out.println("Logged with with => Name: " + user.getName() + "\n Password: " + user.getPassword());
break;
case 2:
Scanner register = new Scanner(System.in);
System.out.print("Enter name: ");
user.setName(register.nextLine());
System.out.print("Enter password: ");
user.setPassword(register.nextLine());
System.out.print("Enter mobile: ");
user.setMobile(register.nextLine());
System.out.print("Enter email: ");
user.setEmail(register.nextLine());
System.out.print("Enter city: ");
user.setCity(register.nextLine());
System.out.print("Enter post code: ");
user.setpostcode(register.nextLine());
if (!hm.containsValue(user.toString())) {
hm.put(UUID.randomUUID().toString(), user.toString());
System.out.println("Account created successfully");
} else {
System.out.println("User already exists");
}
break;
case 3:
//
break;
default:
throw new IllegalArgumentException("Wrong Choice");
}
}
}
}
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);
}
I am trying to retrieve every record that an arraylist contains. I have a class called ContactList which is the super class of another class called BusinessContacts. My first task is to print only the first name and last name of a contact. The second task is to print details of a contact that's related to its id number. The ContactList class has all the instance variables and the set/get methods and the toString() method. The BusinessContact class consists of only two instance variables that need to be appended to the ContactList class. How is can this be worked out? The code is below:
The ContactList class:
package newcontactapp;
public abstract class ContactList {
private int iD;
private String firstName;
private String lastName;
private String adDress;
private String phoneNumber;
private String emailAddress;
// six-argument constructor
public ContactList(int id, String first, String last, String address, String phone, String email) {
iD = id;
firstName = first;
lastName = last;
adDress = address;
phoneNumber = phone;
emailAddress = email;
}
public ContactList(){
}
public void displayMessage()
{
System.out.println("Welcome to the Contact Application!");
System.out.println();
}
public void displayMessageType(String type)
{
System.out.println("This is a " + type);
System.out.println();
}
public int getiD() {
return iD;
}
public void setiD(int id) {
iD = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String first) {
firstName = first;
}
public String getLastName() {
return lastName;
}
public void setLastName(String last) {
lastName = last;
}
public String getAdDress() {
return adDress;
}
public void setAdDress(String address) {
adDress = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phone) {
phoneNumber = phone;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String email) {
emailAddress = email;
}
public String toString(){
return getiD() + " " + getFirstName() + " " + getLastName() + " " + getAdDress() + " " + getPhoneNumber() + " " + getEmailAddress() + "\n" ;
}
}
The BusinessContacts class:
package newcontactapp;
public class BusinessContacts extends ContactList {
private String jobTitle;
private String orGanization;
//
public BusinessContacts(int id, String first, String last, String address, String phone, String email, String job, String organization){
super();
jobTitle = job;
orGanization = organization;
}
public BusinessContacts(){
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String job) {
jobTitle = job;
}
public String getOrGanization() {
return orGanization;
}
public void setOrGanization(String organization) {
orGanization = organization;
}
//#Override
public String toString(){
return super.toString()+ " " + getJobTitle()+ " " + getOrGanization() + "\n";
}
}
Here is my main method class:
package newcontactapp;
import java.util.ArrayList;
//import java.util.Iterator;
import java.util.Scanner;
public class NewContactAppTest {
//ArrayList<ContactList> fullList = new ArrayList<>();
ArrayList<ContactList> bContacts = new ArrayList<>();
ArrayList<ContactList> pContacts = new ArrayList<>();
public static void main(String [] args)
{
ContactList myContactList = new ContactList() {};
myContactList.displayMessage();
new NewContactAppTest().go();
}
public void go()
{
ContactList myContactList = new ContactList() {};
System.out.println("Menu for inputting a Business Contact or Personal Contact");
System.out.println();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a numeric choice below: ");
System.out.println();
System.out.println("1. Add a Business Contact");
System.out.println("2. Add a Personal Contact");
System.out.println("3. Display Contacts");
System.out.println("4. Quit");
System.out.println();
String choice = input.nextLine();
if(choice.contains("1")){
String type1 = "Business Contact";
myContactList.displayMessageType(type1);
businessInputs();
}
else if(choice.contains("2")){
String type2 = "Personal Contact";
myContactList.displayMessageType(type2);
personalInputs();
}
else if(choice.contains("3")) {
displayContacts();
displayRecord();
}
else if(choice.contains("4")){
endOfProgram();
}
}
public void businessInputs()
{
BusinessContacts myBcontacts = new BusinessContacts();
//ContactList myContactList = new ContactList() {};
//ContactList nameContacts = new ContactList() {};
bContacts.clear();
int id = 0;
myBcontacts.setiD(id);
Scanner in = new Scanner(System.in);
while(true){
id = id + 1;
myBcontacts.setiD(id);
//myContactList.setiD(id);
System.out.println("Enter first name ");
String firstName = in.nextLine();
//nameContacts.setFirstName(firstName);
//myContactList.setFirstName(firstName);
myBcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
//nameContacts.setLastName(lastName);
//myContactList.setLastName(lastName);
myBcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
//myContactList.setAdDress(address);
myBcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
//myContactList.setPhoneNumber(phoneNumber);
myBcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
//myContactList.setEmailAddress(emailAddress);
myBcontacts.setEmailAddress(emailAddress);
System.out.println("Enter job title: ");
String jobTitle = in.nextLine();
myBcontacts.setJobTitle(jobTitle);
System.out.println("Enter organization: ");
String organization = in.nextLine();
myBcontacts.setOrGanization(organization);
//bContacts.add(myContactList);
bContacts.add(myBcontacts);
//names.add(nameContacts);
//System.out.println("as entered:\n" + bContacts);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
continue;
}
else{
break;
}
}
//bContacts.add(myBcontacts);
go();
}
public void personalInputs(){
ContactList myContactList = new ContactList() {};
PersonalContacts myPcontacts = new PersonalContacts();
Scanner in = new Scanner(System.in);
int id;
id = 1;
while(true){
System.out.println("Enter first name; ");
String firstName = in.nextLine();
myContactList.setFirstName(firstName);
myPcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
myContactList.setLastName(lastName);
myPcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
myContactList.setAdDress(address);
myPcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
myContactList.setPhoneNumber(phoneNumber);
myPcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
myContactList.setEmailAddress(emailAddress);
myPcontacts.setEmailAddress(emailAddress);
System.out.println("Enter birth date");
String dateOfBirth = in.nextLine();
myPcontacts.setDateOfBirth(dateOfBirth);
//pContacts.add(myContactList);
pContacts.add(myPcontacts);
id = id + 1;
myContactList.setiD(id);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if (choice.equalsIgnoreCase("y")) {
continue;
}
else{
break;
}
}
go();
}
public void displayContacts(){
System.out.println();
for(ContactList name : bContacts){
System.out.println(name.getiD() + " " + name.getFirstName()+ " " + name.getLastName());
}
}
public void displayRecord(){
System.out.println();
System.out.println("Do you wish to see details of contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
System.out.println();
System.out.println("Enter the numeric key from the list to see more specific details of that record");
System.out.println();
Scanner key = new Scanner(System.in);
System.out.println();
ContactList record = new ContactList() {};
for(int i = 0; i < bContacts.size(); i++){
record = bContacts.get(i);
System.out.println(record.toString());
}
}
else{
go();
}
/* else{
System.out.println();
System.out.println("This is a Personal Contact");
System.out.println();
for(int j = 0; j < pContacts.size(); j++){
ContactList pList = pContacts.get(j);
pList = pContacts.get(j);
System.out.println(pList.toString());
}
}*/
}
public void endOfProgram(){
System.out.println("Thank you! Have a great day!");
Runtime.getRuntime().exit(0);
}
}
If you're looking to get a value based on ID, try making a method that iterates over the contents of the ArrayList to find one that matches:
public ContactList getContactList(int id) {
for (ContactList list : /*your ContactList List object*/) {
if (list.getiD() == id) {
return list;
}
}
return null;
}
This will return null if none is found, or the first result in the list.
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);
}
import cs1.Keyboard;
import java.util.Scanner;
class Person
{
private String name;
private String persnr;
private String adress;
private int age;
public Person(String _name, String _persnr, String _adress, int _age)
{
name = name;
persnr = persnr;
adress = adress;
age = age;
}
public void byterNamn(String _name)
{
name = _name;
}
public void byterAdress(String _adress)
{
adress = _adress;
}
public void fyllerAr()
{
age = age + 1;
}
public String hamtaNamn()
{
return name;
}
public String hamtaPersonnmmer()
{
return persnr;
}
public String hamtaAdress()
{
return adress;
}
public int hamtaAlder()
{
return age;
}
public String toString()
{
String _toString;
_toString = "Namn: " + name + "\nÅlder: " + age;
_toString = _toString + "\nPersonnummer: " + persnr + "\nAdress: " + adress;
return _toString;
}
public p1()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "ålder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public p2()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "ålder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public static void main(String[] args)
{
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p1 = new Person(name, age, adress, personnummer);
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p2 = new Person(name, age, adress, personnummer);
}
}
hello.
I try to do so it is 2 people. where you should enter the age, name, address of both people and then print it after you enter what you want when the program runs. and i wondering how do i do return on public p1() and public p2() so i can do it. Or is it a easier way to do it?
This code does not compile. public p1() and public p2() are not valid method declarations. You must at least add a method return type after the public and before the method name, for example:
public Person p1()
Then I guess what you want to do is return a Person object from each of those two methods. Inside the method you must create a new Person object and then return it from the method:
return new Person(name, persnr, adress, age);
See Defining Methods and Returning a Value from a Method in Oracle's Java Tutorials.