Finding and removing a name in an ArrayList - java

Basically i am trying to search for specif names in an Array-list and then remove just that name.I am doing an assignment for college, and it species to search and remove by name, so i cant use the int index of, I am fairly new to java, so ill post my code maybe I am missing something any help would be great.
import java.util.ArrayList;
public class GaaClub {
private ArrayList<Member> players;
{
}
public GaaClub() {
players = new ArrayList<Member>();
}
public void addStanderedMember() {
// create a message object:
StdOut.println("Please enter the members's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the members address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the members DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
Member player = new Member(name, address, dob, mempaid);
players.add(player);
}
public void addStandaredPlayer() {
// create a message object:
StdOut.println("Please enter the standard Player's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the standard Player's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the standard Player's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the amount to Pay: ");
double mempaid = StdIn.readDouble();
StandardPlayer player = new StandardPlayer(name, address, dob, mempaid);
players.add(player);
}
public void addElitePlayer() {
// create a message object:
StdOut.println("Please enter the Elite Players's name: ");
StdIn.readLine();
String name = StdIn.readLine();
StdOut.println("Please enter the Elite Players's address: ");
String address = StdIn.readLine();
StdOut.println("Please enter the Elite Players's DOB: ");
String dob = StdIn.readLine();
StdOut.println("Please enter the the amount to Pay: ");
double mempaid = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's BMI: ");
double bmi = StdIn.readDouble();
StdOut.println("Please enter the Elite Players's height: ");
double height = StdIn.readDouble();
ElitePlayer player = new ElitePlayer(name, address, dob, mempaid, bmi,
height);
players.add(player);
}
public static void main(String[] args) {
GaaClub app = new GaaClub();
app.run();
}
public void memberType() {
StdOut.println("Enter Type of membership: ");
StdOut.println("1) Add a Standard Member");
StdOut.println("2) Add an Elite Player");
StdOut.println("3) Add a Standard Player");
String memberchoice = StdIn.readString();
if (memberchoice.equals("1"))
addStanderedMember();
if (memberchoice.equals("2"))
addElitePlayer();
if (memberchoice.equals("3"))
addStandaredPlayer();
}
public void listNames() {
for (Member player : players) {
player.list();
}
}
public void removeName() {
for (Member player : players) {
listNames();
String sResponse = StdIn.readString();
if (sResponse.equals(player.name))
{
players.remove(player);;
return;
}
}
}
private int mainMenu() {
StdOut.println("1) Add a Member");
StdOut.println("2) Remove Player");
StdOut.println("3) List Names");
StdOut.println("4) List Members");
StdOut.println("0) Exit");
StdOut.print("==>>");
int option = StdIn.readInt();
return option;
}
public void run() {
{
StdOut.println("Posts");
int option = mainMenu();
while (option != 0) {
switch (option) {
case 1:
memberType();
break;
case 2:
removeName();
break;
case 3:
addStanderedMember();
break;
case 4:
listNames();
break;
}
option = mainMenu();
}
StdOut.println("Exiting...");
}
}
}
And Second file:
import java.util.ArrayList;
public class Member {
protected String name;
protected String address;
protected String dob;
protected double mempaid;
public Member(String name, String address, String dob, double mempaid) {
this.name = name;
this.address = address;
this.dob = dob;
this.mempaid = mempaid ;
}
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 getDob() {
return dob;
}
public void list(){
System.out.println(name);
}
public void setDob(String dob) {
this.dob = dob;
}
public double getMempaid() {
return mempaid;
}
public void setMempaid(double mempaid) {
this.mempaid = mempaid;
}
#Override
public String toString() {
return "Member [name=" + name + ", address=" + address + ", dob=" + dob
+ ", mempaid=" + mempaid + "]";
}
}
import java.util.ArrayList;
public class StandardPlayer extends Member {
private ArrayList<Competition> competition;
public StandardPlayer(String name, String address, String dob,
double mempaid) {
super(name, address, dob, mempaid);
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
public void setCopmetition(ArrayList<Competition> copmetition) {
this.competition = copmetition;
}
void addCompetiton(Competition c) {
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "StandardPlayer [competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
}
And third file:
import java.util.ArrayList;
public class ElitePlayer extends Member {
private double bmi;
private double height;
private ArrayList<Competition> competition;
public ElitePlayer(String name, String address,
String dob, double mempaid, double bmi, double height) {
super(name, address, dob, mempaid);
this.bmi = bmi;
this.height = height;
}
public double getBmi() {
return bmi;
}
public void setBmi(double bmi) {
this.bmi = bmi;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public ArrayList<Competition> getCopmetition() {
return competition;
}
void payMembership(double amt) {
mempaid = 0;
}
#Override
public String toString() {
return "ElitePlayer [bmi=" + bmi + ", height=" + height
+ ", competition=" + competition + ", name=" + name
+ ", address=" + address + ", dob=" + dob + ", mempaid="
+ mempaid + "]";
}
public void setCompetition(ArrayList<Competition> competition) {
this.competition = competition;`enter code here`
}
}

ArrayList has a method which can remove by Object:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
arr.remove("Bob");
it removes the first instance of the object.
You could of course simulate the same debavior:
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).equals(searchTerm) {
arr.remove(i);
break;
}
}
This deviation from the built in method would only be recommended if you wanted to have the search delete on some other, or similar condition. For example if it contained the word "Bob"...
ArrayList<String> arr = new ArrayList<String>();
arr.add("Bob Bobingston");
String searchTerm = "Bob";
for (int i = 0; i < arr.size(); i++) {
if (arr.get(i).contains(searchTerm)) {
arr.remove(i);
break;
}
}

It seems as if you already have a loop set-up for it. Just loop through the members, check if the name equals what you're looking for, then remove that member from the list if it is
for(Member mem : players) { //loop through each member in list
if(mem.getName().equalsIgnoreCase("name")) { //check if member's name is "name"
players.remove(mem); //removes member from list if it is
}
}
equalsIgnoreCase(String) checks the string without checking for case sensitivity. It won't care for capitalization. If you care about capitalization, use equals(String)

Related

How can I solve with Java's map containsKey() method?

I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.

Creating an object from a text file using arrays, (no ArrayList), InputMismatchException when running

I'm working on a project where I have to make an array of objects created from a text file. However whenever I run it, I get
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at CustomerList.main(CustomerList.java:16)
Even though the text file starts with an integer. Please look at my code and give me some insight into what I'm doing wrong.
This is part of the text file that I have to read from:
100
900 Amazon purchasing#amazon.com 20000.0 0.08
210 Nordstrom purchasing#nordstrom.com 50000.0 0.07
10 Rutgers purchasing#rutgers.edu 32000.0 education
520 Alamo purchasing#alamo.com 23000.0 0.05
1 Kean purchasing#kean.edu 158000.5 education
100 Allied purchasing#allied.com 85300.0 0.06
950 JoesInc purchasing#joesinc.com 999999.0 0.03
697 BostonU purchasing#tufts.edu 340020.23 education
310 TruckersInc purchasing#truckersinc.com 55000.0 0.10
820 Clothiers purchasing#clothiers.com 20044.0 0.05
849 RedCross purchasing#redcross.org 48900.2 non-profit
125 ChocolateRus purchasing#chocolate.com 3000.5 0.1
import java.util.*;
import java.math.*;
import java.text.*;
import java.io.*;
public class CustomerList {
public static void main(String[] args)throws IOException {
File f = new File("custy.txt");
Scanner in = new Scanner(f);
Customer[] obj = new Customer[1];
int count = 0;
while(in.hasNext() ){
int id = in.nextInt();
String name = in.next();
String email = in.next();
double balance = in.nextDouble();
obj[count] = new Customer (id, name, email, balance);
count++;
}
in.close();
for (int i = 0; i < count; i++)
System.out.println(obj[i]);
}
}
class Customer {
public int custId;
public String name;
public String email;
public double balance;
public Customer() {
this.custId = 0;
this.name = "";
this.email = "";
this.balance = 0.0;
}
public Customer(int custId, String name, String email, double balance) {
this.custId = custId;
this.name = name;
this.email = email;
this.balance = balance;
}
public int getId() {
return custId;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public double getBalance() {
return balance;
}
public void setName(String name) {
this.name = name;
}
public void setId(int custId) {
this.custId = custId;
}
public void setEmail(String email) {
this.email = email;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("$.00");
return custId + " " + dollar.format(balance) + name + " " + email + " ";
}
}class TaxExempt extends Customer {
public String exempt;
public TaxExempt() {
this.exempt = "";
}
public TaxExempt(int custId, String name, String email, double balance, String exempt) {
super(custId, name, email, balance);
this.exempt = exempt;
}
public String getExempt() {
return exempt;
}
public void setExempt(String reason) {
this.exempt = reason;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("$.00");
return custId + " " + name + " " + dollar.format(balance) + " " + email + " " + exempt;
}
}
class NonExempt extends Customer {
public double tax;
public double afterTax;
public NonExempt() {
this.tax = 0.0;
this.afterTax = 0.0;
}
public NonExempt(int custId, String name, String email, double balance, double tax) {
super(custId, name, email, balance);
this.tax = tax;
}
public double getTax() {
return tax;
}
public void setTax(double tax) {
this.tax = tax;
}
public void setAfterTax() {
this.afterTax = tax * balance;
}
public String toString() {
DecimalFormat dollar = new DecimalFormat("$.00");
String add = "%";
// System.out.println("Non Exempt: " );
return custId + " " + name + " " + dollar.format(balance) + " " + email + " " + tax + add + " "
+ dollar.format(afterTax);
}
}
Your error is somewhat related to this question: Scanner is skipping nextLine() after using next() or nextFoo()?
Note: Assuming you removed the first 100 in the file
Your app is crashing because when it gets to
double balance = in.nextDouble();
And tries to iterate one more time, there's nothing in that line for
int id = in.nextInt();
To read from, all you need is to include:
in.nextLine();
After
double++;
And you should get your desired output.
Complete code as example:
import java.util.*;
import java.math.*;
import java.io.*;
class Test {
public static void main(String[] args)throws IOException {
File f = new File("custy.txt");
Scanner in = new Scanner(f);
while(in.hasNext() ){
int id = in.nextInt();
String name = in.next();
String email = in.next();
double balance = in.nextDouble();
in.nextLine();
System.out.println(id + " " + name + " " + email + " " + balance);
}
in.close();
}
}
The above code prints:
900 Amazon purchasing#amazon.com 20000.0
210 Nordstrom purchasing#nordstrom.com 50000.0
10 Rutgers purchasing#rutgers.edu 32000.0
520 Alamo purchasing#alamo.com 23000.0
1 Kean purchasing#kean.edu 158000.5
100 Allied purchasing#allied.com 85300.0
950 JoesInc purchasing#joesinc.com 999999.0
697 BostonU purchasing#tufts.edu 340020.23
310 TruckersInc purchasing#truckersinc.com 55000.0
820 Clothiers purchasing#clothiers.com 20044.0
849 RedCross purchasing#redcross.org 48900.2
125 ChocolateRus purchasing#chocolate.com 3000.5

Displaying a multiple object arraylist?

I am curious as to how would I show a multiple object arraylist in Java. The array list contains both string and int.
This is the class of which I am making a arraylist of.
public class Movie
{
public int rating;
public String title, directorName, actorOne, actorTwo, actorThree;
public Movie(String Title, String Director, String ActorOne, String ActorTwo, String ActorThree, int Rating)
{
title = Title;
directorName = Director;
actorOne = ActorOne;
actorTwo = ActorTwo;
actorThree = ActorThree;
rating = Rating;
}
public void setTitle(String Title)
{
title = Title;
}
public String getTitle()
{
return title;
}
public void setDirector(String Director)
{
directorName = Director;
}
public String getDirector()
{
return directorName;
}
public void setActorOne(String ActorOne)
{
actorOne = ActorOne;
}
public String getActorOne()
{
return actorOne;
}
public void setActorTw0(String ActorTwo)
{
actorTwo = ActorTwo;
}
public String getActorTwo()
{
return actorTwo;
}
public void setActorThree(String ActorThree)
{
actorThree = ActorThree;
}
public String getActorThree()
{
return actorThree;
}
}
This is my main class
import java.io.*;
import java.util.*;
public class Database
{
Scanner input = new Scanner(System.in);
boolean start;
ArrayList<Movie> movie = new ArrayList<Movie>();
String title, director, actOne, actTwo, actThree;
int rating;
public Database()
{
// initialise instance variables
this.display();
}
public void display()
{
while (start = true)
{
System.out.println("Welcome to the Movie Database");
System.out.println
(
"Select an option \n" +
"1 Find Movie \n" +
"2 Add Movie \n" +
"3 Delete Movie \n" +
"4 Display Favourtite Movies \n" +
"5 Exit Database \n"
);
int choice = input.nextInt();
input.nextLine();
switch(choice)
{
case 1:
break;
case 2:
this.addMovie();
break;
case 3:
break;
case 4:
break;
case 5:
this.exit();
break;
default:
System.out.println("Invalid selection.");
break;
}
}
}
public void exit()
{
System.out.println("Exiting");
start = false;
System.exit(0);
}
public void addMovie()
{
System.out.println("Insert Movie Name: ");
title = input.nextLine();
System.out.println("Insert Director Name: ");
director = input.nextLine();
System.out.println("Insert Actor One Name: ");
actOne = input.nextLine();
System.out.println("Insert Actor Two Name: ");
actTwo = input.nextLine();
System.out.println("Insert Actor Three Name: ");
actThree = input.nextLine();
System.out.println("Insert Movie Rating: ");
rating = input.nextInt();
movie.add(new Movie(title, director, actOne, actTwo, actThree, rating));
}
}
I just wish to see if I my program is actually adding to array list.
Thank you
You may find helpful overriding toString method in the movie class and then printing the arrayList everytime you do something with it...
System.out.println("actual state of the list: "+movie);
and override the toString method in the movie class... somthing descripting the object... like:
#Override
public String toString() {
return "Movie [rating=" + rating + ", title=" + title + ", directorName=" + directorName + ", actorOne="
+ actorOne + ", actorTwo=" + actorTwo + ", actorThree=" + actorThree + "]";
}

How to create an arraylist using polymorphism?

I am trying to create an array list that contains all employees and is able to handle any type of employee. I also have to load the data onto to the list The class I'm using is called payroll. This is what I have so far:
The employee class looks like this:
import java.util.*;
public abstract class Employee
{
private String name, employeeNum, department;
private char type;
public Employee()
{
name ="";
employeeNum = "";
department = "";
}
public Employee(String Name, String EmpNum, String Depart)
{
name = Name;
employeeNum = EmpNum;
department = Depart;
}
//public EMpoy
public String getName()
{
return name;
}
public String getEmployeeNum()
{
return employeeNum;
}
public String getDepartment()
{
return department;
}
public char getType()
{
return type;
}
public void setName(String Name)
{
name = Name;
}
public void setEmployeeNum(String EmpNum)
{
employeeNum = EmpNum;
}
public void setDepartment(String Depart)
{
department = Depart;
}
public String toString()
{
String str;
str = "Employee Name: " + name + "\n"
+ "Employee Number: " + employeeNum + "\n"
+ "Employee Department: " + department + "\n";
return str;
}
}
The payroll class looks like this so far:
import java.util.*;
import java.io.*;
public class Payroll
{
private ArrayList<Employee> list = new ArrayList<Employee>();
private String fileName;
public Payroll()
{
}
public void fileName(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("InsertFileName");
String fileName1 = kb.next();
fileName = fileName1 + ".txt";
}
public void loadData() throws FileNotFoundException
{
Scanner s = new Scanner(new File(fileName));
while (s.hasNext())
{
String name = s.next();
String employeeNum = s.next();
String department = s.next();
//String typeString = s.next();
//char type = typeString.toUpperCase().charAt(0);
char type = s.next().toUpperCase().charAt(0);
if (type == 'S')
{
double yearlySalary = s.nextDouble();
list.add(new Salary (name, employeeNum, department, yearlySalary));
}
else if (type == 'H')
{
double hourlyPayRate = s.nextDouble();
String hours = s.next();
int hoursWorked = Integer.parseInt(hours);
list.add(new Hourly (name, employeeNum, department, hourlyPayRate, hoursWorked));
}
else if (type == 'C')
{
int numOfWeeks = s.nextInt();
double baseWeeklySalary = s.nextDouble();
int salesThisWeek = s.nextInt();
int salesThisYear = s.nextInt();
double commissionRate = s.nextDouble();
list.add(new Commission (name, employeeNum, department, numOfWeeks, baseWeeklySalary, salesThisWeek, salesThisYear, commissionRate));
}
}
s.close();
}
Now I know I'm supposed to make the arraylist in the constructor, that's what I'm having trouble with. How can I make the list using polymorphism to get every employee? Thanks.
Hi Srk93 You are getting error as your list contains the references of Employee class and Employee class does't have getCommissionRate method. You can call on Employee reference which are declared in Employee class. Create abstact method of calculateSalary() and implement in all your child classes.
Its duplicate of "cannot find symbol: method" but the method is declared

Creating a contact list with java and object oriented

I am new to programming and object oriented design. This is my last requirement to finish my bachelors degree (not in programming). I am so confused with how to make object oriented work, and nothing I look at seems to help.
The assignment is to create a contact list that uses inheritance, polymorphism,and collections. I need a contact list that is stores two types of contacts: business and personal.
1. Prompt to select which contact to add or display.
2. Prompt to allow user to enter the contact info.
3. Prompt that will display the output of a chosen contact back.
I have the following class and subclasses. I am stuck on how I am supposed to read in the inputs to the specific arraylists. I don't even know if the classes are built right either.
Any help would be awesome, I just need to get through this, then I will gladly leave programing to those that know what they are doing.
This is what I have for my Parent Class:
package ooo1;
public abstract class Contact {
private String contactId;
private String firstName;
private String lastName;
private String address;
private String phoneNumber;
private String emailAddress;
public Contact(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;
}
void displayContact(){
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);
}
}
This is one of my subclasses:
package ooo1;
public class PersonalContact extends Contact {
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;
}
}
This is my other subclass:
package ooo1;
public class BusinessContact extends Contact {
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 setJobTitle(String input){
this.jobTitle = input;
}
public String getJobTitle(){
return this.jobTitle;
}
public void setOrganization(String input){
this.organization = input;
}
public String getOrganization(){
return this.organization;
}
}
This is what I have for Main which is so wrong at this point I believe:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
ArrayList<PersonalContact> personalList = new ArrayList<PersonalContact>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
}
}
You have the pieces in place you just need to put them together. First, think about the List being used. It is supposed to hold both types of contacts, however its type argument is using the derived type PersonalContact. Instead use the base class Contact
List<Contact> contacts = new ArrayList<Contact>();
Next it appears you start to gather the information about the contact from the end user via the console. Before doing this you may want to ask what type of contact is being entered, maybe give the option to enter 1 for a personal contact or 2 for a business contact. Then collect the information specific to the type of contact they chose.
Scanner input = new Scanner(System.in);
System.out.println("Please enter Specify the contact type (1 Personal, 2 Business) : ");
int contactType = input.nextInt();
//collect data common to both types
if(contactType == 1){
//collect information specific to personal
} else if(contactType ==2){
//collect information specific to business
}
Next you need to turn the data you collected into the actual objects, using a the constructors. This will need to be done conditionally and could actually be a part of the last section if done properly.
Contact contact;
if(contactType == 1){
contact = new PersonalContact(/*arguments here*/);
} else{
contact = new BusinessContact(/*arguments here*/);
}
Then finish up by adding the contact to your list:
contacts.add(contact);
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
/**
*
* #author Arijit
*/
public class Contact {
private String name;
private int number;
public Contact(int number,String name) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public static Contact createContact(int number, String name){
return new Contact(number,name);
}
}
This is the Contact class, which is governed by a contact name and a contact number. Next we will design the MobilePhone class which will have a number(optional) and an arraylist of contacts.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
import java.util.ArrayList;
/**
*
* #author Arijit
*/
class MobilePhone1 {
public int mynumber;
public ArrayList < Contact > contacts;
public MobilePhone1(int mynumber) {
this.mynumber = mynumber;
this.contacts = new ArrayList < Contact > ();
}
public Boolean addContact(Contact contact) {
if (findPosition(contact) >= 0) {
System.out.println("Contact already is phone");
return false;
} else {
contacts.add(contact);
}
return true;
}
public ArrayList < Contact > getContacts() {
return contacts;
}
public void updateContact(Contact oldContact, Contact newContact) {
if (findPosition(oldContact) >= 0) {
contacts.set(findPosition(oldContact), newContact);
} else {
System.out.println("Contact does not exist");
}
}
public void removeContact(Contact contact) {
if (findPosition(contact) >= 0) {
contacts.remove(findPosition(contact));
} else {
System.out.println("No contact");
}
}
public int searchContact(Contact contact) {
int position = findPosition(contact);
if (contacts.contains(contact)) {
System.out.println("Item found at position");
return position;
}
System.out.println("Not found");
return -1;
}
private int findPosition(Contact contact) {
return this.contacts.indexOf(contact);
}
private int findPosition(String name) {
for (int i = 0; i < contacts.size(); i++) {
Contact contact = this.contacts.get(i);
if (contact.getName().equals(name)) {
return i;
}
}
return -1;
}
}
public class MobilePhone {
public static void main(String args[]) {
Boolean quit = false;
int choice = 0;
java.util.Scanner sc = new java.util.Scanner(System.in);
MobilePhone1 phone = new MobilePhone1(98312);
//Contact newcontact = Contact.createContact(12345,"Arijt");
while (!quit) {
System.out.println("Enter your choice");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 0:
System.out.println("Enter the number of Contacts");
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
int phoneNumber = sc.nextInt();
System.out.println("Enter Name");
sc.nextLine();
String name = sc.nextLine();
Contact newcontact = Contact.createContact(phoneNumber, name);
phone.addContact(newcontact);
}
break;
case 1:
int size = phone.getContacts().size();
System.out.println(size);
for (int i = size - 1; i >= 0; i--) {
phone.removeContact(phone.getContacts().get(i));
}
System.out.println(phone.getContacts().isEmpty());
break;
case 2:
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.searchContact(phone.getContacts().get(i)));
}
break;
case 3:
//Contact newcontact1 = Contact.createContact(12345,"Buzz");
System.out.println("Enter the Contact name you want to update");
String oldContactName = sc.nextLine();
for (int j = 0; j < phone.getContacts().size(); j++) {
if (phone.getContacts().get(j).getName().equals(oldContactName)) {
System.out.println("Enter the new Contact name");
String newName = sc.nextLine();
System.out.println("Enter the new Contact number");
int newNumber = sc.nextInt();
phone.updateContact(phone.getContacts().get(j), Contact.createContact(newNumber, newName));
} else {
System.out.println("You are looking for the wrong contact");
}
}
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.getContacts().get(i).getName() + "," + phone.getContacts().get(i).getNumber());
}
break;
case 4:
if(phone.getContacts().isEmpty()){
System.out.println("Emtpty contact list");
}
else {
System.out.println("Contact list");
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println("Name: "+phone.getContacts().get(i).getName() + ",Phone Number: " + phone.getContacts().get(i).getNumber());
}
}
break;
case 6:
System.out.println("Enter 0 for adding contact\n");
System.out.println("Enter 1 for removing every contact\n");
System.out.println("Enter 2 for searching contact\n");
System.out.println("Enter 3 for updating contact\n");
System.out.println("Enter 4 for viewing the contact list\n");
System.out.println("Enter 6 for exiting\n");
System.out.println("Enter 5 to see the instrusctions again\n");
break;
case 5:
quit = true;
break;
}
}
}
}

Categories