In the driver, it correctly finds the position, but I tried using contacts.remove(foundPosition) ... And the 'Contact' was not deleted.
How can I delete the entire 'Contact' That the user searched for?
Driver:
import java.util.Collections;
import java.util.ArrayList;
import java.util.Scanner;
public class contactDriver
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
// Asks you to enter values from the given menu.
int answer;
System.out.println ("Press 1 to add a contact."); // Menu is printed.
System.out.println ("Press 2 to display all contacts.");
System.out.println ("Press 3 to search for a contact.");
System.out.println ("Press 4 to search for a contact to delete.");
answer = scan.nextInt();
// ArrayList
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("Patrick", "McGee", "334-555-8860", "pmcgee123#gmail.com"));
contacts.add(new Contact("John", "Appleseed", "142-555-6740", "jappleseed99#gmail.com"));
contacts.add(new Contact("Matt", "Jordan", "213-555-2323", "mjordan23#gmail.com"));
contacts.add(new Contact("Kanye", "East", "255-434-9909", "keast123#gmail.com"));
contacts.add(new Contact("Derrick", "Flower", "144-555-1111", "dflower1#gmail.com"));
// If statements for the user's decision.
if (answer == 4){ // User searches for a contact and chooses whether or not to delete the contact.
System.out.println("Enter the first name of the contact to search for.");
String fname = scan.next();
scan.nextLine();
System.out.println("Enter the last name of the contact to search for.");
String lname = scan.next();
scan.nextLine();
Collections.sort(contacts);
for(Contact c : contacts)
System.out.println(c);
int foundPosition = Collections.binarySearch(contacts, new Contact(fname, lname, "", ""));
System.out.println(foundPosition);
// The found contact may or may not be deleted.
String answer2;
System.out.println("Would you like to delete this contact? (y/n)");
answer2 = scan.next();
if (answer2 == "y"){
contacts.remove(foundPosition); // **HERE is where I need help.**
System.out.println ("Contact is deleted. Here is the updated contact list: ");
for(Contact c : contacts)
System.out.println(c);
}
if (answer2 == "n"){
System.out.println("Contact will not be deleted.");
}
}
}
}
Class containing methods:
import java.util.Collections;
import java.util.ArrayList;
import java.util.Comparator;
public class Contact implements Comparable<Contact>
{
public Contact(String fname, String lname, String num, String email)
{
this.fname = fname;
this.lname = lname;
this.num = num;
this.email = email;
}
public String getFirstname()
{
return fname;
}
public String getLastname()
{
return lname;
}
public String getNum()
{
return num;
}
public String getEmail()
{
return email;
}
public int compareTo(Contact other)
{
if (fname.compareTo(other.lname) == 0)
return fname.compareTo(other.fname);
return lname.compareTo(other.lname);
}
public String toString()
{
return "Contact[" + fname + ", " + lname + ", " + num + ", " + email + "]";
}
private String fname;
private String lname;
private String num;
private String email;
}
Comparator:
import java.util.Comparator;
class ContactComparator implements Comparator<Contact>
{
public int compare(Contact a, Contact b)
{
if (a.getFirstname().compareTo(b.getFirstname()) == 0)
return a.getFirstname().compareTo(b.getFirstname());
return a.getLastname().compareTo(b.getLastname());
}
}
Thanks.
The reason why remove(int) is not working is because is not executed.
In your case is that you wrongly compare reference type.
if (answer2 == "y"){
contacts.remove(foundPosition); // **HERE is where I need help.**
When using objects to check that are equal you should call method equals
if ("y".equalsIgnoreCase(answer2)){ // **HERE is where You needed help.**
contacts.remove(foundPosition);
You can read more about it here:
How do I compare strings in Java?
Related
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.
I have the following 3 classes that is meant to represent a program that allows a user to create a sort of database that can add people and their phone numbers and addresses and then search for them once created.
Here are the classes:
Person
import java.util.*;
public class Person implements Comparable<Person> {
private final String name;
private String street;
private String city;
private String address;
public Person(String name) {
this.name = name;
this.address = "address unknown";
}
public String getName() {
return name;
}
public void setAddress(String street, String city){
this.city = city;
this.street = street;
this.address = this.street + " " + this.city;
}
public String getAddress() {
return address;
}
#Override
public int compareTo(Person o) {
return this.name.compareToIgnoreCase(o.getName());
}
}
PhoneNumbers (to store the person + their phone numbers)
import java.util.*;
import java.util.Collections;
public class PhoneNumbers {
private Map<Person, Set<String>> numbers;
public PhoneNumbers() {
this.numbers = new HashMap<Person, Set<String>>();
}
public void addPhoneNumber(Person person, String phoneNumber){
if(!this.numbers.keySet().contains(person)){
this.numbers.put(person, new HashSet<String>());
}
this.numbers.get(person).add(phoneNumber);
}
public Set<String> searchByPerson(Person person){
if(!this.numbers.keySet().contains(person)){
return this.numbers.get(person);
}
return null;
}
public String searchByNumber(String number){
for(Person person : this.numbers.keySet()){
Set<String> x = this.numbers.get(person);
for(String y : x){
if(y.equals(number)){
return person.getName();
}
}
}
return " not found";
}
public void personalSearch(Person person){
System.out.println(" " + person.getAddress());
if(this.numbers.get(person).size() == 0){
System.out.println(" phone number not found");
}
for(String x : this.numbers.get(person)){
System.out.println(" phone numbers");
System.out.println(" " + x);
}
}
public void remove(Person person){
this.numbers.remove(person);
}
public List<Person> masterSearch(String search){
ArrayList<Person> names = new ArrayList<Person>();
for(Person person : this.numbers.keySet()){
if(person.getName().contains(search) || person.getAddress().contains(search)){
names.add(person);
}
}
Collections.sort(names);
return names;
}
public Map<Person, Set<String>> getNumbers() {
return numbers;
}
}
UI (to provide the way for the user to interact with the program)
import java.util.Scanner;
public class UI {
private Scanner reader;
private PhoneNumbers phoneNumbers;
public UI() {
this.reader = new Scanner(System.in);
this.phoneNumbers = new PhoneNumbers();
}
public void start(){
System.out.println("phone search\n" +
"available operations:\n" +
" 1 add a number\n" +
" 2 search for a number\n" +
" 3 search for a person by phone number\n" +
" 4 add an address\n" +
" 5 search for personal information\n" +
" 6 delete personal information\n" +
" 7 filtered listing\n" +
" x quit\n");
while(true){
System.out.print("command: ");
int command = Integer.parseInt(reader.nextLine());
System.out.println("");
if(command == 1){
System.out.print("whose number: ");
String name = reader.nextLine();
System.out.print("number: ");
String number = reader.nextLine();
Person person = new Person(name);
this.phoneNumbers.addPhoneNumber(person, number);
}
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
//something here
}
}
else{
System.out.println(" not found");
}
}
}
}
}
I have a question with the code in the UI specifically
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
when the command is given as 2 I ask the user for a name and that is given as a string, how do I then use that String to find the value of the person object with that name under the HashMap i.e. the set of numbers associated with the person.
Obviously I cannot do this with a get method on the map as the keys are person objects not strings and I don't know what to do (do I need to store a map between String name and Person name), I believe in this context names are unique?
Also bonus question: why would I be getting an error when I do command 1 and give a number that is not all digits like "045-4558" for instance.
Thank you
Maybe something like that:
for (Map.Entry<Person, Set<String>> entry : numbers.entrySet()) {
Person key = entry.getKey();
if (key.getName().equals(nameWhichYouAreLookingFor)) {
//Do whatever you want
}
}
// to create address object, and pass the address to faculty
// Must connect to other classes simultaneously
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Driver {
public static ArrayList<Student> student = new ArrayList<Student>();
public static ArrayList<Course> course = new ArrayList<Course>();
public static ArrayList<FacultyMember> faculty = new ArrayList<FacultyMember>();
public static void main(String[] args) {
String[] choices = { "0 Exit", "1 Add Student", "2 List of Students",
"3 Remove Student", "4 Create course", "5 List of Courses",
"6 Remove Course", "7 add instructor", "8 List of Instructors",
"9 Remove Instructor" };
student.add(new Student(308765433, "phillip", 2436, "Daly Street",
"Los Angeles", "CA", "USA"));
student.add(new Student(308765434, "Wilson Lucey", 2436,
"Broadway Street", "Los Angeles", "CA", "USA"));
student.add(new Student(308765432, "William", 2436,
"University Street", "Los Angeles", "CA", "USA"));
course.add(new Course(23545, "CS201"));
course.add(new Course(23546, "CS202"));
course.add(new Course(23547, "CS203"));
faculty.add(new FacultyMember(23477, "John"));
// faculty.add(new FacultyMember(23587, "Keenan"));
// faculty.add(new FacultyMember(236, "Parviz"));
int a = -1;
while (a < 0) {
int choice = JOptionPane.showOptionDialog(null, "Welcome", "Menu",
a, a, null, choices, a);
if (choice == 0) {
System.exit(0);
}
if (choice == 1) { // DONE
addStudent();
}
if (choice == 2) { // List all students inside array of students.
String a1 = "";
for (Student b : student) {
// b.toString();
a1 = a1 + b.toString() + "\n";
}
JOptionPane.showMessageDialog(null, a1);
}
if (choice == 3) {
removeStudent();
}
if (choice == 4) { // Show all courses inside array of courses
addCourse();
}
if (choice == 5) { // List of Course
String c1 = "";
for (Course b : course) {
// b.toString();
c1 = c1 + b.toString() + "\n";
}
JOptionPane.showMessageDialog(null, c1);
}
if (choice == 6) {
removeCourse();
}
if (choice == 7) {
addFaculty();
}
if (choice == 8) { // LIST OF FACULTY
String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";
}
JOptionPane.showMessageDialog(null, d1);
}
if (choice == 9) { // REMOVE FACULTY
removeFaculty();
}
}
}
private static void addStudent() {
int CIN = Integer.parseInt(JOptionPane.showInputDialog("Enter CIN: "));
String Name = JOptionPane.showInputDialog("Enter name");
// int street, String name, String city, String state, String country
int Street = Integer.parseInt(JOptionPane
.showInputDialog("Enter street #"));
String StreetName = JOptionPane.showInputDialog("Enter Street Name");
String City = JOptionPane.showInputDialog("Enter city");
String State = JOptionPane.showInputDialog("Enter state");
String Country = JOptionPane.showInputDialog("Enter country");
Student s1 = new Student(CIN, Name, Street, StreetName, City, State,
Country);
student.add(s1);
}
private static void addCourse() { // If
int courseID = Integer.parseInt(JOptionPane
.showInputDialog("Enter the id numer please!"));
String courseTitle = JOptionPane
.showInputDialog("Enter a course please!");
// String instructorName = JOptionPane
// .showInputDialog("Enter instructor for the course please!");
Course c1 = new Course(courseID, courseTitle); // CREATE OBJECT
course.add(c1);
}
// private static void Course(int courseID, String courseTitle, String term,
// String instructorName) {
//
// }
private static void addFaculty() {
int employeeID = Integer.parseInt(JOptionPane
.showInputDialog("Enter the employee id numer please!"));
String facultyName = JOptionPane
.showInputDialog("Enter the name of faculty please!"); // SAME
// AS
// STUDENTS
FacultyMember f1 = new FacultyMember(employeeID, facultyName);
faculty.add(f1);
}
public static void removeStudent() {
String a1 = "";
int i = 0;
for (Student b : student) {
// b.toString();
a1 = a1 + i++ + b.toString() + "\n";
}
int LineNumber = Integer.parseInt(JOptionPane.showInputDialog(null, a1
+ "Enter a row # to remove, please"));
student.remove(LineNumber);
for (int k = 0; k < student.size(); k++) {
System.out.println(student.get(k));
}
}
public static void removeCourse() {
String a1 = "";
int i = 0;
for (Course b : course) {
// b.toString();
a1 = a1 + i++ + b.toString() + "\n";
}
int LineNumber = Integer.parseInt(JOptionPane.showInputDialog(null, a1
+ "Enter a row # to remove, please"));
course.remove(LineNumber);
for (int k = 0; k < course.size(); k++) {
System.out.println(course.get(k));
}
}
public static void removeFaculty() {
String b1 = "";
int i = 0;
for (FacultyMember b : faculty) {
// b.toString();
b1 = b1 + i++ + b.toString() + "\n";
}
// JOptionPane.showMessageDialog(null,
// a1+"Enter a row # to remove, please");
//
int LineNumber = Integer.parseInt(JOptionPane.showInputDialog(null, b1
+ "Enter a row # to remove, please"));
faculty.remove(LineNumber);
for (int k = 0; k < faculty.size(); k++) {
System.out.println(faculty.get(k));
}
}
}
// }
public class Address {
/*
* An address has a street number, street name, city, state or province, and
* country.
*/
private int street;
private String name;
private String city;
private String state;
private String country;
public Address(int street, String name, String city, String state, String country) {
this.street = street;
this.name = name;
this.city= city;
this.state = state;
this.country = country;
}
public int getStreet() {
return street;
}
public void setStreet(int street) {
this.street = street;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity(String city){
return city;
}
public void setCity(String city){
this.city=city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String toString() {
return name + " "+
"Street: "+street+ " "+
"City: "+city+ " , "+ " State: "+ state +
"Country: "+country;
}
}
public class Person {
/*
* A Person has a name and an Address (represented by an object of class
* Address, not a String). Note that the subclasses of Person inherit the
* fields and methods of Person. You may need to override some of the
* methods in the subclasses.
*/
protected String name;
protected Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(int street, String name, String city, String state,
String country) {
Address set1 = new Address(street, name, city, state, country);
this.address = set1;
}
public String toString() {
return "Name: " + name + " "+"Address: " + address.toString();
}
}
public class Course {
private int identifier;
private String courseTitle;
public Course(int identifier, String courseTitle){
this.identifier= identifier;
this.courseTitle= courseTitle;
}
public int getIdentifier() {
return identifier;
}
public String getCourseTitle() {
return courseTitle;
}
public String toString(){
return "Course ID: "+identifier + "Course title: "+ courseTitle;
}
public boolean contains(Course course) {
// TODO Auto-generated method stub
return false;
}
//setter to change the object values
//getters is to return some values we need
}
import java.util.ArrayList;
import java.util.List;
public class FacultyMember extends Person{
private int employeeID;
public ArrayList<Course>course = new ArrayList<Course>();
public FacultyMember(int employeeID, String nameIn){
this.name= nameIn;
this.employeeID = employeeID;
}
public int getID(){
return employeeID;
}
public void setID(int employeeID){
this.employeeID = employeeID;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public List<Course> getCourse(){
return course;
}
public void addCourse(Course course) {
this.course.add(course);
}
public String toString(){
return "EmployeeID: " + employeeID +super.toString() ;
}
}
Write a Driver class that maintains lists of Students, Courses, and
FacultyMembers and has a menu that provides ways to list, create, and delete
them based on user input. The driver class should also provide a way for a
student to add and drop existing Courses and a way to assign faculty member
to teach existing Courses. Do not create a new Course when a Student adds or
when a faculty member is assigned to teach; let the user choose a Course from
the list. Think about how to organize this input before you start coding.
Include a method that can be called from main that will use your methods to
add and delete some hard-coded test data (several students, several faculty
members, and several courses.) This will let you code the lists and test the
methods to add and delete items without using the user input functions.
I am having difficulty with my Faculty Member class I am getting this error
Exception in thread "main" java.lang.NullPointerException
at Person.toString(Person.java:30)
at FacultyMember.toString(FacultyMember.java:33)
at Driver.main(Driver.java:83)
As said earlier, you are calling toString on the address instance variable in your Person class, but you never instantiate the variable, meaning it has the default value for an Object: null.
If you try to call a member of a non instantiated variable, it will throw a NullPointerException.
public String toString() {
return "Name: " + name + " "+"Address: " + address.toString();
}
Either remove the toString call for address, or make sure you instantiate it.
That being said, there is much that can be improved on your code:
code like this:
if (choice == 6) {
removeCourse();
}
if (choice == 7) {
addFaculty();
}
if (choice == 8) { // LIST OF FACULTY
String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";
}
JOptionPane.showMessageDialog(null, d1);
}
if (choice == 9) { // REMOVE FACULTY
removeFaculty();
}
is not efficiƫnt. I think we can both agree, that if choice == 6, choice will never (at the same time) have the value7, 8 or 9, yet you still test for them.
One way to improve this, is using else statements:
if (choice == 6) {
removeCourse();
}else if (choice == 7) {
addFaculty();
} else if (choice == 8) { // LIST OF FACULTY
String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";
}
JOptionPane.showMessageDialog(null, d1);
}else if (choice == 9) { // REMOVE FACULTY
removeFaculty();
}
When you do this, it will not check if choice has one of the values, if it already found the value it has in a previous test. So, if choice == 6, it will not test for 7, 8 or 9.
Even though this is a lot better, it 's still not very easy to read. a switch statement can help here:
switch(choice){
case 6: removeCourse();
break;
case 7: addFaculty();
break;
case 8: String d1 = "";
for (FacultyMember d : faculty) {
// b.toString();
d1 = d1 + d.toString() + "\n";}
JOptionPane.showMessageDialog(null, d1);
break;
case 9: removeFaculty();
break;
}
Add proper indentation to that, and you'll have a lot easier to maintain code.
No doubt there is more you can improve, but this 'll give you something to start with.
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;
}
}
}
}
I am trying to print out the results of the users inputs to a simple text file but everything I have tried has rendered unsuccessful. I tried using a PrintWriter within the switch case but the results still just printed out null. I am quite new to Java so maybe I am missing obvious?
Here is the code:
package parkingsystem;
import java.io.*;
import java.util.Scanner;
public class Registration {
static String [][] userData;
static String [][] fileData;
public static void Registration(){
Scanner input = new Scanner(System.in);
String lotNo;
String First;
String Last;
String studentID;
String phoneNo;
String email;
String carNo;
String dateReg;
String strcontent;
String proceed;
boolean proceed2 = true;
userData = new String [50][6];
fileData = new String [50][6];
int counter = 0;
int col;
int row;
boolean carry_on = true;
MainMenu choices = new MainMenu();
while(proceed2=true){
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
proceed = input.nextLine();
switch (proceed) {
case "Y":
case "y":
System.out.println("Enter your student ID");
studentID = input.nextLine();
System.out.println("Enter your first name");
First = input.nextLine();
System.out.println("Enter your last name");
Last = input.nextLine();
System.out.println("Enter your car number");
carNo = input.nextLine();
System.out.println("Enter your contact number");
phoneNo = input.nextLine();
System.out.println("Enter your email address");
email = input.nextLine();
row = counter ;
userData [row][0] = studentID;
userData [row][1] = First;
userData [row][2] = Last;
userData [row][3] = carNo;
userData [row][4] = phoneNo;
userData [row][5] = email;
if (counter == 6){
carry_on=false;
}
proceed2 = false;
break;
case "N":
case "n":
choices.Menus();
break;
}
}
}
}
Here's a second pass at re-factoring your code.
So now in this refactoring we capture and store the newly created CarOwner objects and store them in a list.
Then we see how to go through that List of CarOwner's and then write those objects to a file called carOwners.dat
Ordinarily, in industry, code re-factoring is done in the context of having a set of unit tests against which you can ensure that the refactoring hasn't broken the required behaviour of the code but we are just learning here so this work serves to explain some of the concepts that you are missing and this first pass iteration below has some issues of its own so don't take this as the final product.
Refactorings
I have created a CarOwner class.
I have renamed the Boolean variable canProceed so that it reads more naturally.
Update : I have made the CarOwner class Serializable; this will allow us to write the Object to a File.
Update : I have added code that up the new CarOwners and adds it to a List and then I iterate over the list to write those CarOwner objects to a FileStream.
package parkingsystem;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.FileOutputStream;
import java.util.Scanner;
public class Registration {
public static void main(String[] args) {
List carOwners = new ArrayList();
Scanner input = new Scanner(System.in);
boolean canProceed = true;
while (canProceed) {
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
String optionRequested = input.nextLine();
if (optionRequested.equalsIgnoreCase("Y")) {
CarOwner owner = new CarOwner();
System.out.println("Enter your student ID");
owner.setStudentID(input.nextLine());
System.out.println("Enter your first name");
owner.setFirst(input.nextLine());
System.out.println("Enter your last name");
owner.setLast(input.nextLine());
System.out.println("Enter your car number");
owner.setCarNo(input.nextLine());
System.out.println("Enter your contact number");
owner.setContactNumber(input.nextLine());
System.out.println("Enter your email address");
owner.setEmail(input.nextLine());
owner.setDateReg(new Date().toString());
carOwners.add(owner);
} else if (optionRequested.equals("N") || optionRequested.equals("n")) {
canProceed = false;
}
}
ObjectOutputStream objectWriter = null;
for (CarOwner carOwner : carOwners) {
try {
objectWriter = new ObjectOutputStream(new FileOutputStream("carOwners.dat"));
objectWriter.writeObject(carOwner);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here's what the CarOwner class now looks like ...
package parkingsystem;
import java.io.Serializable;
public class CarOwner implements Serializable{
private String First;
private String Last;
private String studentID;
private String email;
private String carNo;
private String dateReg;
private String contactNumber;
public CarOwner() {
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getLast() {
return Last;
}
public void setLast(String last) {
Last = last;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCarNo() {
return carNo;
}
public void setCarNo(String carNo) {
this.carNo = carNo;
}
public String getDateReg() {
return dateReg;
}
public void setDateReg(String dateReg) {
this.dateReg = dateReg;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactNumber() {
return contactNumber;
}
#Override
public String toString() {
return "CarOwner{" +
"First='" + First + '\'' +
", Last='" + Last + '\'' +
", studentID='" + studentID + '\'' +
", email='" + email + '\'' +
", carNo='" + carNo + '\'' +
", dateReg='" + dateReg + '\'' +
", contactNumber='" + contactNumber + '\'' +
'}';
}
}
Ok so creating the CarOwner class is done to make a start at making this code more object oriented.
Secondly the re-factored code demonstrates correct use of a Boolean variable in Java.
As the other commentators have already pointed out the assignment operator = is easily confused with the test for Boolean equality. See Java Operators
Also I have renamed Boolean proceed; to be Boolean canProceed; This is a common strategy. Naming a Boolean variable to read as a question to which the "answer" is, yes or no, or True or False.
This then means we can write code like while(canProceed) which reads very easily. See also if statement on the Java tutorial
I hope this helps.