How to add valid input into arraylist? - java

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);
}

Related

extracting combined string from arraylist

I am scanning three different inputs and converting them into a single string using toString. Then I want to edit the individual inputs.
For example:
name phoneNumber address
sarmad 12345 myhouse
How can I edit 'myhouse'?
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> arraylist = new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();
int choice;
String phoneNumber;
String name,address;
String format = "Empty";
int x = 1;
int flag = 0;
do{
try{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice = Integer.parseInt(input.next());
switch (choice){
case 1:{
System.out.println("Enter name ");
name = input.next();
System.out.println("Enter phone number");
phoneNumber = input.next();
System.out.println("Enter address");
address = input.next();
format = FormatObject.toString(phoneNumber, name, address);
arraylist.add(format);
flag++;
}
break;
case 2:{
System.out.println("Name Phone number Address");
System.out.println();
for(int i = 0; i < flag; i++){
System.out.println(arraylist.get(i));
}
}
break;
default:{
System.out.println("Enter right choice");
}
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice");
}
} while(x == 1);
}
}
my toString method:
public class CreateFormat {
String phoneNumber;
String nameUser;
String addressUser;
public String toString(){
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
public String toString (String phone,String name,String address){
phoneNumber = phone;
nameUser = name;
addressUser = address;
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
}
What you need here is to implement setters/getters for your properties.
public class CreateFormat {
private String phoneNumber;
private String nameUser;
private String addressUser;
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
// Similar set & get methods for other properties too.
}
i allowed myself to make some changes to your code, because my understanding is, that it would be easier and smother to give up String and use the Object itself instead.
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
ArrayList<CreateFormat> arrayList = new ArrayList<CreateFormat>();
int choice;
String phoneNumber;
String name; //sepperated for readability
String address;
//String format="Empty"; not used anymore
int x = 1;
//int flag = 0; is not necessary
do{
try{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice = input.nextInt();//Integer.parseInt(input.next());
switch (choice){
case 1:{
System.out.println("Enter name ");
name = input.next();
System.out.println("Enter phone number");
phoneNumber = input.next();
System.out.println("Enter address");
address = input.next();
arraylist.add(new CreateFormat(name, phoneNumber, address)); //changed to an object of type CreateFormat instead of String
//flag++; not necessary
}
break;
case 2:{
//System.out.println("Name Phone number Address");
//System.out.println();
for(int i=0;i<arrayList.size();i++){// size = method from the ArrayList library
System.out.println("Name:" + arrayList.get(i).getNameUser());
System.out.println("Phone Number:" + arrayList.get(i).getPhoneNumber());
System.out.println("Address:" + arrayList.get(i).getAddressUser());
//System.out.println(arraylist.get(i));
}
}
break;
default:{
System.out.println("Enter right choice");
}
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice");
}
}while(x==1);
}
}
Create Format:
public class CreateFormat {
String phoneNumber;
String nameUser;
String addressUser;
public CreateFormat(String phoneNumber, String nameUser, String addressUser){
this.phoneNumber = phoneNumber;
this.nameUser = nameUser;
this.addressUser = addressUser;
}
public String getPhoneNumber(){
return this.phoneNumber;
}
public String getNameUser(){
return this.nameUser;
}
public String getAddressUser(){
return this.addressUser;
}
}
I couldn't test it yet, so feel free to ask if there are some issues.

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 do you retrieve all of the records that a user inputs into an arraylist in java

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.

Person tester application with inheritance and abstract classes

I apologize in advance if there is more posts about this, I have looked through the postings that appeared relevant but could not find a solution. I working on a project called a Person Tester in which;
the user is prompted to chose between creating a customer (c) or an employee (e).
next, the user is prompted to enter first, last name, e-mail adress and either customer number (if customer is selected), or social security number (if employee is selected).
once the correct data has been gathered, the information is suposed to be printed to the console in this format:
name: first last
email: jondoe#fakemail.com
social security number: XXXXXXXXXXX (if employee)
customer number: XXXXXX (if customer)
this program deals with inheritance and an abstract person class which is extended by an employee class and a customer class. another stipulation states that the person class should contain an abstract method named getDisplayText that returns a string.
this is where my problem lies, this is my first time working with abstract classes.
MY QUESTION is why cant I simply print the toString method in my perosn class to display all the user data that was entered which brings me to my next issue, the program needs to have an additional component which is (and I quote from my assignment) : To print the data for an object to the console, this application should use a static method named print that accepts a Person object.
im not sure how to implement this since it was never discussed in class. I have tried to simply code the following : System.out.print(aPerson.toString) but all i get is blank value of Name: and Social Security number: . Im going nuts i have been working on this for several hours and re-read the relevant text at least 4 times. this is my last resort. please guide me in the right direction i dont mind working long hours to do this right.
I have written the majority of the application and am now just stuck on how to print the data to the console. any and all suggestions are appreciated, this is my code:
public class CH08PR82App {
public static void main(String[] args) {
System.out.print("Welcome to the Person Tester Application");
System.out.println();
Scanner sc = new Scanner(System.in);
Person aPerson;
aPerson = new Person();
if (aPerson != null) {
System.out.println(aPerson.toString());
}
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
//prompt user to enter customer or employee
System.out.print("Create customer or employee (c/e): ");
String userType = sc.nextLine();
if (userType.equalsIgnoreCase("c")) {
String firstName = Validator.getStringInput(sc, "Enter first name: ");
String lastName = Validator.getStringInput(sc, "Enter last name: ");
String email = Validator.getStringInput(sc, "Enter email address: ");
String custNumber = Validator.getStringInput(sc, "Customer number: ");
//System.out.println(custNumber);
} else if (userType.equalsIgnoreCase("e")) {
String firstName = Validator.getStringInput(sc, "Enter first name: ");
String lastName = Validator.getStringInput(sc, "Enter last name: ");
String email = Validator.getStringInput(sc, "Enter email address: ");
int empSoc = Validator.getInt(sc, "Social security number: ");
}
choice = Validator.getStringContinue(sc, "Continue? (y/n): ");
}
}
}
abstract class Person {
private String firstName;
private String lastName;
private String eMail;
public Person() {
firstName = "";
lastName = "";
eMail = "";
}
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 geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
#Override
public String toString() {
return "Name: " + this.firstName + this.lastName + "\n" + "E-mail: "
+ this.eMail;
}
abstract String getDisplayText();
}
abstract class Customer extends Person {
private String customerNumber;
public Customer() {
super.toString();
customerNumber = "";
}
public void setcustomerNumber(String customerNumber) {
this.customerNumber = customerNumber;
}
public String getcustomerNumber() {
return customerNumber;
}
#Override
public String toString() {
return super.toString() + "Social Security number: " + customerNumber
+ "\n";
}
}
abstract class Employee extends Person {
private String socNumber;
public Employee() {
super.toString();
socNumber = "";
}
public void setsocNumber(String socNumber) {
this.socNumber = socNumber;
}
public String getsocNumber() {
return socNumber;
}
#Override
public String toString() {
return super.toString() + "Social Security number: " + socNumber
+ "\n";
}
}
class Validator {
public static String getStringContinue(Scanner sc, String prompt) {
boolean isValid = false;
String s = "";
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNext("y")) {
s = sc.nextLine(); // read entire line
isValid = true;
} else if (sc.hasNext("n")) {
s = sc.nextLine();
isValid = true;
} else {
s = sc.nextLine();
isValid = false;
System.out.println("Error! Invalid string value. Try again.");
}
}
return s;
}
public static String getStringInput(Scanner sc, String prompt) {
boolean isValid = false;
String s = "";
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNext()) {
s = sc.nextLine(); // read entire line
isValid = true;
} else {
System.out.println("Error! Invalid string value. Try again.");
}
}
return s;
}
public static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
isValid = true;
} else {
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(Scanner sc, String prompt, int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println("Error! Number must be greater than " + min
+ ".");
} else if (i >= max) {
System.out.println("Error! Number must be less than " + max
+ ".");
} else {
isValid = true;
}
}
return i;
}
public static double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public static double getDouble(Scanner sc, String prompt, double min,
double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d <= min) {
System.out.println("Error! Number must be greater than " + min
+ ".");
} else if (d >= max) {
System.out.println("Error! Number must be less than " + max
+ ".");
} else {
isValid = true;
}
}
return d;
}
}
Let's take a look at the print method first:
public static void print(Person person) {
System.out.println(person.toString());
}
Now you need an abstract method in your Person class:
public abstract String getDisplayText(Person person);
Which you will override in your Employee and Customer classes:
// Employee
#Override
public String getDisplayText(Person person) {
return ((Employee)person).toString();
}
and:
// Customer
#Override
public String getDisplayText(Person person) {
return ((Customer)person).toString();
}
They wanted you to make the method abstract because each implementation is different - Customer has a customer ID, Employee has a Soc Number.
Now lets explain static and abstract methods: The difference between a static and abstract method is that an abstract method is just a header - implementation lies on children classes. Whereas a static method means that you can call it without creating an object in the first place.
Usage of this specific static method is very simple. Lets say you have:
Person john = new Customer();
... // Fill john with data
Person.print(john);
It also looks to me like you are a bit confused about all this abstract and static stuff. An abstract class is a class which can't create objects. In your example, you have an abstract class Person. The class is abstract because you either need a customer or an employee (both of which are people, hence the inheritance from Person class), but you don't want to store info about a person who is none of these. And that is also the reason why you can't do:
Person john = new Person(); // Build error
but you can (and should) do:
Person john = new Employee(); // Will compile and run

(non-static method Change(String,String,String) cannot be referenced from a static context

I've searched, but didn't understand how to incorporate previous answers with my own code. I have an assigment to create a draft of a program for the schools "bank/scholarship"-system. Here we need to create a lot of different methods, that should be called instead of just doing the change directly.
The thing is, I keep getting the error-message in the topic along with a few others, and I don't know how to fix it. I would really appreciate if someone could explain for me how and why to change one of my methods, then I assume I will be able to rewrite all the others myself. Here is my code so far:
class Address
public class Address {
public String street, zip, post;
public Address (String street, String zip, String post) {
this.street = street;
this.zip = zip;
this.post = post;
}
// these are setters (mutators)
public void setStreet (String street) {
this.street = street; }
public void setZip (String zip) {
this.zip = zip; }
public void setPost (String post) {
this.post = post; }
// these are getters
public String getStreet () {
return this.street; }
public String getZip () {
return zip; }
public String getPost () {
return post; }
// methods
//public Address Change(Address newAddress) {
//return newAddress;
//}
// output
public String toString() {
return (street + ", " + zip + ", "+ post); }
}
class Customer
import java.text.DecimalFormat;
public class Customer {
DecimalFormat twoD = new DecimalFormat("0.00");
Address address = new Address("Vik ", "6393 ", "Tomrefjord");
public String name, campus, newCampus, newAddress;
public double loan, increase,decrease,regMaster;
public boolean finished;
public Customer (String name,Address address, String campus, double loan, boolean finished) {
this.name = name;
this.campus = campus;
this.loan = loan;
this.address = address;
this.finished = finished;
}
// these are setters
public void setName (String name) {
this.name = name; }
public void setCampus (String campus) {
this.campus = campus; }
public void setLoan (double loan) {
this.loan = loan; }
public void setFinished (boolean finished) {
this.finished = finished; }
// these are getters
public String getName () {
return name; }
public String getCampus () {
return campus; }
public double getLoan () {
return loan; }
// methods
public void RegMaster () {
this.loan = loan * 0.90;}
//public void changeAddress (Address newAddress) {
//Address.Change(newAddress); }
public double decreaseLoan (double currentBalance, double decrease) {
currentBalance = currentBalance - decrease;
return currentBalance; }
public double getNewLoan (double currentBalance, double newLoan) {
newLoan = currentBalance + newLoan;
return newLoan; }
public String getNewCampus (String newCampus) {
campus = newCampus;
return campus; }
public static boolean Ended () {
return true; }
// output
public String toString() {
return (name + "\t\n" + address + "\t\n" + campus + "\t\n" + twoD.format(loan) + "\t\n" + finished); }
}
class TestCustomer
import java.util.Scanner;
public class TestCustomer {
public static void main (String[] args) {
String student, school, answer, street, zip, post;
double balance, master;
boolean finished = false;
double done = 0; //this is for the loop
Scanner scan = new Scanner(System.in);
// a new student receives a loan
System.out.println("Write your name");
student = scan.nextLine();
System.out.println("Enter your street name and number");
street = scan.nextLine();
System.out.println("What is your zip code?");
zip = scan.nextLine();
System.out.println("What is your post area?");
post = scan.nextLine();
System.out.println("Where do you study?");
school = scan.nextLine();
System.out.println("Input your current loan");
balance = scan.nextDouble();
Address residence = new Address(street, zip, post);
Customer customer = new Customer(student, residence, school, balance, finished);
while(done < 1) { //the variable done will have the value 0 until you are finished.
// change address
System.out.println("Do you wish to change your address? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) { //this made it case-insensitive, and now it is not skipping anymore...
System.out.println("Write your street name and house number");
street = scan.nextLine();
System.out.println("Write your zip code");
zip = scan.nextLine();
System.out.println("Write your post area");
post = scan.nextLine();
//Address newAddress = new Address(street, zip, post);
//residence = Customer.changeAddress(newAddress);
}
// increase the loan
System.out.println("Do you want to increase your loan? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("How much do you need?");
double increaseLoan = scan.nextDouble();
//customer.balance = getNewLoan(customer.balance, moreLoan);
}
// decrease the loan
System.out.println("Do you want to make a downpayment on your loan?");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("How much do you intend to pay?");
double downpayment = scan.nextDouble();
//customer.balance = decreaseLoan(customer.balance, downpayment);
}
// change school
System.out.println("Do you study at the same school? (yes/no");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("no")) {
System.out.println("Write the name of the new school");
school = scan.nextLine(); }
//school.getNewCampus(customer.campus);
// master check
System.out.println("Have you finished your master? (yes/no)");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
customer.finished = Customer.Ended() ; //this will set finished to true, using the method like intended
//customer.balance = Customer.RegMaster(); // dont know how to invoke it... me neither -_-
}
System.out.println("Are you done? yes/no");
answer = scan.nextLine();
if (answer.equalsIgnoreCase("yes")) {
done = 1; } // this adds 1 to the variable done, thus ending the loop.
}
// output
System.out.println("");
System.out.println("The data we have so far is:");
System.out.println(customer);
}}
Here are all three of my classes. Some of the functions are commented away, others are just not working properly (the code is also a little extra messy, I was changing back and forth to try to get it working yesterday). Any help will be appreciated! :)
Okay, from you comment then your problem comes from the (helpfully) commented out lines
//public void changeAddress (Address newAddress) {
//Address.Change(newAddress); }
This is because your Customer done not "have an" Address, you need an address instance and not a String:
private Address address;
public Customer (final Address address) {
this.address = address;
}
I have redacted other variables for clarity. Incidentally I would use a builder pattern rathen than one enormous constructor.
Now that you have an Address in your Customer:
public void changeAddress (Some parameters to change) {
address.setStuff();
}
I would recommend that you read this link about the difference between static and instance variables.

Categories

Resources