Constructors and get and set methods togther in java - java

Hi there I have this code at the moment as a basic program which just gets a persons name, phone number and account number and then prints it out in the main method.
import java.util.Scanner;
public class CustomerData {
String name;
String phoneNumber;
String accountCode;
String setname() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers name ?");
String name = scanner.nextLine();
return name;
}
String setNumber() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers Phone Number ?");
String phone = scanner.nextLine();
return phone;
}
String setAccountCode() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers account code ?");
String account = scanner.nextLine();
scanner.close();
return account;
}
public void getInfo() {
System.out.println("\nCustomer Name: "+this.name);
System.out.println("Customer Phone Number: "+this.phoneNumber);
System.out.println("Customer Account Code: "+this.accountCode);
}
}
public class BankAccountTest {
public static void main(String args[]) {
CustomerData p1 = new CustomerData();
p1.name = p1.setname();
p1.phoneNumber = p1.setNumber();
p1.accountCode = p1.setAccountCode();
p1.getInfo();
}
}
However I want to use a constructor like this in my object
import java.util.Scanner;
public class CustomerData {
String name;
String phoneNumber;
String accountCode;
CustomerData(String name, String phoneNumber, String accountCode){
this.name = name;
this.phoneNumber = phoneNumber;
this.accountCode = accountCode;
}
CustomerData(){
this.name = "Unknown";
this.phoneNumber = "Unknown";
this.accountCode = "No Registered Account Code";
}
String setname() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers name ?");
String name = scanner.nextLine();
return name;
}
String setNumber() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers Phone Number ?");
String phone = scanner.nextLine();
return phone;
}
String setAccountCode() {
Scanner scanner = new Scanner(System.in);
System.out.println("What is customers account code ?");
String account = scanner.nextLine();
scanner.close();
return account;
}
public void getInfo() {
System.out.println("\nCustomer Name: "+this.name);
System.out.println("Customer Phone Number: "+this.phoneNumber);
System.out.println("Customer Account Code: "+this.accountCode);
}
}
Is it then okay to reuse the same main method with this constructor added or will I need to change my main method.

No, you don't need to change your main method. You can call the parametrized constructor like -
CustomerData p1 = new CustomerData("Mary", "9191919191", "12345");

Related

How do i take user input and store it successfully in an ArrayList? Then how do i get my program to show me all the elements in the ArrayList?

I want a program that stores details about staff in an arraylist. I'd like to prompt user for input and store each result in the arraylist. How do I do this? And how do i view everything stored in the arraylist after?
It doesn't need to reflect the code I have, just can't seem to figure out how i have a class with setters and getters and then create a new main class promting user for input and store that input in the arraylist.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class salesPersonMain {
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
//ask user for input and get input
System.out.println("Enter id: ");
int id = Integer.parseInt(input.nextLine());
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
List<salesPerson> sPerson = new ArrayList<salesPerson>();
sPerson.add(new salesPerson(id, firstName, lastName));
}
}
I have another class for the salesperson:
import java.util.ArrayList;
public class salesPerson<sPerson> {
//create variables for sales person
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) throws InputValidationException {
if (firstName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.firstName = firstName;
}
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName)throws InputValidationException {
if (lastName.matches("\\p{Upper}(\\p{Lower}){2,20}")) {
} else {
throw new InputValidationException();
}
{
this.lastName = lastName;
}
}
//creates array of salespeople
private ArrayList<sPerson> salesPerson;
public salesPerson() {
salesPerson = new ArrayList<>();
}
//adds new salesperson to the array
public void add(salesPerson sPerson) {
salesPerson.add((sPerson) sPerson);
}
You'll need a loop to repeatedly get the input:
public static void main(String[] args) throws InputValidationException {
Scanner input = new Scanner(System.in);
List<salesPerson> sPerson = new ArrayList<salesPerson>();
// Loop forever
// Need a way to break the loop. One option: have the user
// input "q" for quit
while (true) {
//ask user for input and get input
System.out.println("Enter id ('q' to quit): ");
String temp = input.nextLine();
if (temp.equals("q")) break;
int id = Integer.parseInt(temp);
// This should be in try/catch in case parseInt fails
System.out.println("Enter first name:");
String firstName = input.nextLine();
System.out.println("Enter last name:");
String lastName = input.nextLine();
//save in array list
sPerson.add(new salesPerson(id, firstName, lastName));
}
// Print the list
sPerson.forEach(System.out::println);
}
So it prints out properly, you need to override the toString function in the salesPerson class:
public class salesPerson {
// Other code here.....
#Override
public String toString() {
return id + "," + firstName + " " + lastName;
}
}

System.out.print doesnt display customer data

I am writing a client database. I want to know the customer's name and hometown based on the customer number. When I enter number 2, I want to see Arya Stark, Edinburgh and when I enter number 1, I want to see Jon Snow, London. Why doesn't my program work? How to fix this?
package app;
import java.util.Scanner;
class Person {
String name;
String homeCity;
int customerNumber;
}
public class Customers {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String name;
System.out.print ("Give a customer card number: ");
name = input.next();
Person person1 = new Person();
person1.name = "Jon Snow";
person1.homeCity = "London";
person1.customerNumber = 1;
Person person2 = new Person();
person2.name = "Arya Stark";
person2.homeCity = "Edinburgh";
person2.customerNumber = 2;
System.out.println();
}
}
This should work:
class Person {
private String name;
private String homeCity;
private int customerNumber;
public Person(String name, String homeCity, int customerNumber) {
this.name = name;
this.homeCity = homeCity;
this.customerNumber = customerNumber;
}
public boolean isMatch(int num) {
return num == customerNumber;
}
#Override
public String toString() {
return name + " from " + homeCity;
}
}
import java.util.Scanner;
class Main {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Person person1 = new Person("Jon Snow", "London", 1);
Person person2 = new Person("Arya Stark", "Edinburgh", 2);
while(true) {
System.out.print("Give a customer card number: ");
String num = input.next();
if (person1.isMatch(Integer.parseInt(num))) {
System.out.println(person1);
} else if (person2.isMatch(Integer.parseInt(num))) {
System.out.println(person2);
} else {
System.out.println("Not found");
}
}
}
}

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.

Java issues with console menu

I have created a functioning console menu and I will choose an option to add a new customer, as you can see below I have created the scanner to enter the details, what I dont know is how I would save the user input out to a text file called CustomerInformation. I can either do this with a function on this method or if there is some way to store the information and create a save function before I quit out of the console menu.
public void addCustomer()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
this.name = sc.nextLine();
System.out.print("Enter Address: ");
this.address = sc.nextLine();
System.out.print("Enter Gender(M or F): ");
this.gender = sc.nextLine();
System.out.print("Enter Date of Birth: ");
this.dob = sc.nextLine();
}
the whole customer class is:
import java.util.*;
import java.io.*;
public class Customer {
private String name;
private String address;
private String gender;
private String dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
Customer (){
setName("Name");
setAddress("Address");
setGender("Gender");
setDob("dDob");
}
Customer (String strName, String strAddress, String strGender, String strDob, String strReport){
setName(strName);
setAddress(strName);
setGender(strGender);
setDob(strDob);
}
//Add Customer Function-------------------------------------------------------------------
public void addCustomer()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
this.name = sc.nextLine();
System.out.print("Enter Address: ");
this.address = sc.nextLine();
System.out.print("Enter Gender(M or F): ");
this.gender = sc.nextLine();
System.out.print("Enter Date of Birth: ");
this.dob = sc.nextLine();
}
//End Add Customer-------------------------------------------------------------------------
//Search Function-------------------------------------------------------------------------
//End Search Function-------------------------------------------------------------------
//Delete Customer Function ------------------------------------------------------
//End Delete Customer Function---------------------------------------------------------
//Save Progress Function--------------------------------------------------------------
//End Save Progress Function----------------------------------------------------------
public static int nextInt()
{
Scanner keyb = new Scanner(System.in);
int i = keyb.nextInt();
return i;
}
}
This is Test class.read writeCustomerToFile method.this is not difficult.i hope you will figure out:
public final class Test {
public static void main(String[] args) {
Customer customer = new Customer();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Name: ");
customer.setName(sc.nextLine());
System.out.print("Enter Address: ");
customer.setAddress(sc.nextLine());
System.out.print("Enter Gender(M or F): ");
customer.setGender(sc.nextLine());
System.out.print("Enter Date of Birth: ");
customer.setDob(sc.nextLine());
writeCustomerToFile(customer,"D:/yourfilename.txt");
}
public static void writeCustomerToFile(Customer customer, String fileName) {
PrintWriter writer = null;
try {
writer = new PrintWriter(fileName, "UTF-8");
writer.println("name:" + customer.getName());
writer.println("address:" + customer.getAddress());
writer.println("gender:" + customer.getGender());
writer.println("birth date:" + customer.getDob());
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
} finally {
writer.close();
}
}
}
Your customer class is the same not changed

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.

Categories

Resources