JAVA - HELP adding comparable interface and arrays into my class - java

I got a lab assignment dealing with arrays, sorting them and adding comparable interface to my two classes. I have to modify a Customer class so it implements a comparable interface. Then I have to sort an array of objects created by this class.
These are the steps outlined by my worksheet:
open the customer and SortedCustomersApp java files (see below):
public class Customer
{
private String email;
private String firstName;
private String lastName;
public Customer(String email, String firstName, String lastName)
{
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return email;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
}
This is the sorted customers app:
import java.util.Arrays;
public class SortedCustomersApp
{
public static void main(String[] args)
{
}
}
add code to the customer class to implement the comparable interface. The compareTo method you create should compare the email field of the current customer with the email field of another customer. To do that you cant use the < or > operators because the email field is a string. Instead, use the compareToIgnoreCase method of the string class. This method compares the string it's executed on with the string that's passed to it as an argument. If the first string is less than the 2nd string, this methods returns a negative integer. if the first string is greater than the second string, it returns a positive integer. And if the 2 strings are equal, it returns 0.
3.Add code to the SortedCustomersApp class that creates an array of Customer objects that can hold 3 elements, and create and assign Customer objects to those elements. Be sure that the email values you assign to the objects aren't in alphabetical order. Sort the array.
code a "for each" loop that prints the email, firstName, and lastName fields of each Customer object on a separate line.
compile and test the program
This program needs to have user input for email, firstName, and lastName but when I tried adding user input to the customer app I got errors saying I cant convert a string to scanner type, but the user inputs need to be a string so that's also a problem.

you implement Comaprable in order to define for Collections.sort() what criteria you use compare instances.For example if I was to compare students by their grades:
public class Student implements Comparable<Student>{
int age;
int grade;
//this method is used in Collections.sort() to determine what is bigger
//for me its grades that matter so that's what I do in code
#override
compareTo(Student other){
if(this.grade>other.grade){
return 1;
}else if(grade<other.grade){
return -1;
}
return 0;
}
}
then you just create an ArrayList students for example and call
Collections.sort(students)
EDIT: to answer you question in comments. If you use a Collection like ArrayList you would call Collections.sort() , if you use a regular array, then Arrays.sort(). In both cases the Objects to be sorted need to implement Comparable just like I showed you.

You can compare two String's lexicographically calling compareTo method on String object, code looks like this
public class Customer implements Comparable<Customer>{
private String email;
public Customer(String email) {
this.email = email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
#Override
public int compareTo(Customer otherCustomer) {
return this.email.compareToIgnoreCase(otherCustomer.email);
}
#Override
public String toString() {
return "Customer{" +
"email='" + email + '\'' +
'}';
}
}
You can sort list of objects using Collections.sort method
List<Customer> list = new ArrayList<>();
list.add(new Customer("abc#bc.com"));
list.add(new Customer("des#bc.com"));
list.add(new Customer("bbc#bc.com"));
list.add(new Customer("aec#bc.com"));
Collections.sort(list);

modified customer class
public class Customer implements Comparable<Customer>{
:
public int compareTo(Object obj)
{
Customer cus = (Customer) obj;
// write your comparison code here
// return 1, 0, or -1 on the basis of your requirement
}
:
}
Then perform
Collection.sort(customerList);
in main method to sort the data.
There is two ways to take String as an input from user:
1) Buffered Reader
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String email = reader.readLine(); // email, firstname etc.
2) Scanner Class
Scanner input = new Scanner(System.in);
String email = input.next();
Now create an Customer object and add setter method to set the value.

Related

Store array of objects into text file in Java

I need help with saving an array to a text file. So I have the following array
private Passenger[] queueArray = new Passenger[30];
and this is the class that I have
public class Passenger
{
private String firstName;
private String surname;
private int secondsInQueue;
Passenger(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
secondsInQueue = 0;
}
public String getName()
{
return firstName + " " + surname;
}
public void setName(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
public Integer geSeconds()
{
return secondsInQueue;
}
public void setSecondsInQueue(Integer SecondsInQueue)
{
this.secondsInQueue = SecondsInQueue;
}
public void display()
{
System.out.println(firstName + " " + surname + " " + secondsInQueue);
}
}
I need to save the first name and the surname of the passengers to a text file. And then I need to read the file back to the array.
I am literally so stuck... Any help would be appreciated.
Thank You!
Change the class implementation as below, to support java serialization. No methods to implement, it is a marker interface.
import java.io.*;
public class Passenger implements Serializable {}
Then you can write the objects in to any file with any extension. Then using java deserialization you can read the object array and iterate it through. Refer to this article, it has a simple example https://www.javatpoint.com/serialization-in-java.
At the time you de-serialize the object, you can call the getter method for the array object and iterate it through.
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
YourClass s=(YourClass)in.readObject();
Passenger[] pasngrArray = s.getPassengerArray(); // call a method to get the array
for (Passenger p : pasngrArray){
// your code to access the two properties here.
}

Data structure for storing phonebook data

What would be the best data structure to store phone book contacts, each consisting of first name, last name and phone number. The user must be able to search by each one of the fields.
There has been similar questions, but none of the answers were clear enough.
Create a POJO type, that stores first name, last name, and phone number (could make it mutable if needed).
class PhoneBookEntry {
public final String firstName;
public final String lastName;
public final String phoneNumber;
public Entry(String firstName, String lastName, String phoneNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
}
//... equals + hashcode implementation
}
You can create your phone book like this:
class PhoneBook {
private Map<String, Set<PhoneBookEntry>> firstNameMap;
private Map<String, Set<PhoneBookEntry>> lastNameMap;
private Map<String, Set<PhoneBookEntry>> phoneNumberMap;
public void add(PhoneBookEntry entry) {
Set<PhoneBookEntry> set
= firstNameMap.computeIfAbsent(entry.firstName, k -> new HashSet<>());
set.add(entry);
set = lastNameMap.computeIfAbsent(entry.lastName, k -> new HashSet<>());
set.add(entry);
set = phoneNumberMap.computeIfAbsent(entry.phoneNumber, k -> new HashSet<>());
set.add(entry);
}
public Set<PhoneBookEntry> getByFirstName(String firstName) {
return firstNameMap.get(firstName);
}
public Set<PhoneBookEntry> getByLastName(String lastName) {
return lastNameMap.get(lastName);
}
public Set<PhoneBookEntry> getByPhoneNumber(String phoneNumber) {
return phoneNumberMap.get(phoneNumber);
}
}
Using Maps allows for fast lookup.
As yitzih said, Multiple contacts can have the same first name, last name, or phone number. So a lookup by first name (for instance), will return a set of contacts.
Create a Contact object that stores the variables needed for each contact. Use an ArrayList to store them.
Without having more information about the contact there isn't really any way to use a HashTable, Map or Graph. There is no real key value pair for a HashTable unless you want to use a combination of first and last names, but you would need some way to handle conflicts (if 2 people have the exact same name.), or you would need to forbid having 2 people having the same Contact name (but why would you want to do that?)
Class Contact{
String forename;
String Surname;
String phoneNo;
public Contact(fName, sName, pNo){
forename = fName;
Surname = sName;
phoneNo = pNo;
}
public String getForename(){}
public String getSurname(){}
public String getPhoneNo(){}
}
in the class handling the search,
you declare an arrayList of type Contact, and when searching for a contact say John,
public Contact searchContact(String s){
for(int i = 0; i< ContactList.size(); i++){
if(ContactList.get(i).getForename().equals(s) ||
ContactList.get(i).getSurame().equals(s) ||
ContactList.get(i).getPhoneNo().equals(s)
){
return ContactList.get(i);
}
}
return null;
}
Kind of a vague question, but what the heck, maybe this'll chase away my post-lunch sleepies. I'm assuming a simple String representation of the phone number, but the best data object to store all the possible varieties of world phone numbers along with a method to intelligently search them (e.g. is "(123) 456-7891" the same as "1234567891"?) could be it's own question entirely.
Here a PhoneBook class stores all of the contacts. The methods searchFirst(), searchLast() and searchPhoneNumber() each return lists of matching contacts.
public class PhoneBook {
ArrayList<Contact> contacts;
public PhoneBook() {
contacts = new ArrayList<>();
}
public void addContact(Contact contact) {
contacts.add(contact);
}
public ArrayList<Contact> searchFirst(String first) {
ArrayList<Contact> foundContacts = new ArrayList<>();
for (Contact contact: contacts) {
if (contact.first.equals(first)) {
foundContacts.add(contact);
}
}
return foundContacts;
}
public ArrayList<Contact> searchLast(String last) {
ArrayList<Contact> foundContacts = new ArrayList<>();
for (Contact contact: contacts) {
if (contact.last.equals(last)) {
foundContacts.add(contact);
}
}
return foundContacts;
}
public ArrayList<Contact> searchPhoneNumber(String phoneNumber) {
ArrayList<Contact> foundContacts = new ArrayList<>();
for (Contact contact: contacts) {
if (contact.phoneNumber.equals(phoneNumber)) {
foundContacts.add(contact);
}
}
return foundContacts;
}
class Contact {
String first;
String last;
String phoneNumber;
public Contact(String first, String last, String phoneNumber) {
this.first = first;
this.last = last;
this.phoneNumber = phoneNumber;
}
}
}

Getters in Java for novice java users

Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are
Abstraction
Encapsulation
Suppose we have an Employee class:
package com.highmark.productConfig.types;
public class Employee {
private String firstName;
private String middleName;
private String lastName;
public void getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
// Similarly for lastName
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
}
UPDATE : Is this usage right with the workerclass?
public class getNames() {
private String firstName;
private String middleName;
private String lastName;
//Constructor
public String getNames() {
Scanner input = new Scanner();
// output message to insert name part
String firstName = input.ReadLine();
String middleName = input.ReadLine();
String lastName = input.ReadLine();
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setMiddleName(middleName);
emp.setLastName(lastName);
}
}
Please try to explain the flaw in understanding if any.
Yes, you are correct on one thing for sure. Getters are Setters are a way to ensure the principle of Encapsulation in Object Oriented Programming languages like Java.
When you have a private member in your class, then its scope gets restricted to that particular class itself, but you may want to provide getters and/or setters to make that member accessible to classes outside your class.
Suppose you have a member like this,
private String firstName;
then this is your getter for this member,
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
but this is not,
public String getFirstName() {
Scanner user_input = new Scanner(System.in);
firstName = user_input.next( );
return firstName;
}
because "getter" is just a term used to get the value of a member which is private. The sole purpose of a getter method is just to get the original value of a member.
In the latter method, the purpose is absolutely different. You are trying to get the first name as input, so technically it cannot be called a "getter" in any way.
Hope this clears your doubt.

Finding index of more than one object

I create this code just for my own understanding. I have a person class and a List to store all my Person objects. I added the same object twice to illustrate my question. How do I find the index of those objects?
How do I find the indexes of the two Andy Bernards?
public class Person {
private String firstName;
private String lastName;
public Person(String firstName,String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override public String toString()
{
return String.format(this.firstName + " " + this.lastName);
}
}
List<Person> deletePeople = new ArrayList<Person>();
Person createPerson = new Person("Andy","Bernard");
Person createTwo = new Person("Micheal","Scott");
deletePeople.add(createPerson);
deletePeople.add(createTwo);
deletePeople.add(createPerson);
/* for (Person display : deletePeople) {
if(display.getFirstName().equals("Andy")) {
System.out.println(deletePeople.indexOf(display));
}
} */
}
Firstly, add .equals() and .hashCode() methods to class Person so you can identify a Person object as being the same.
Second, use indexOf() and lastIndexOf() methods in class List to find the first and last Andy Bernard objects.
If what you really want is a list of indexes into the list where objects match your criteria, and there can be more than one, then you will need to iterate the list yourself, and save the indexes to some sort of list.
If what you want is simply to delete the matching items, then you can use java.util.Iterator (see http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html) to iterate over the collection, and invoke the Iterator's remove() method on each matching object as you encounter it.

Creating a class with different argument lengths

How do I create a class that has different lengths of arguments?
public static void main(String[] args) {
group g1 = new group("Redskins");
group g2 = new group("Zack", "Mills", 21);
group g3 = new group("John","Smith",20);
group g4 = new group("Fred","Fonsi",44);
group g5 = new group("Jeb","Bush",26);
System.out.println(g1.getName());
}
}
I want to be able to display the team name (redskins) and then each member after that using one method.
I've tried using two methods and got that to work, but can't get one.
I was thinking about possibly using an array but not sure if that would work.
Thanks for any help.
I have three classes the main, student, and group.
I need the group class to display the group name and then figure out how to display the students information underneath. The only thing, is that my assignment is vague about whether I can use two methods or one.
public class student {
String firstName;
String lastName;
int age;
student(String informedFirstName, String informedLastName, int informedAge){
firstName = informedFirstName;
lastName = informedLastName;
age = informedAge;
}
String getName()
{
return "Name = " + firstName + " " + lastName + ", " + "Age = " + age;
}
}
public class Team{
String name;
Set<Player> players;
public Team(String name){
this.name = name;
}
public void addPlayer(Player p){
players.add(p);
}
}
public class Player{
String name;
etc
}
EDIT for revised question:
Ok, Im going to show a lot here. Heres what a proper Java versio of what you want for student.
public class Student {
private String firstName;
private String lastName;
private int age;
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/*
* Use:
* Student s = new Student(Bill, Nye, 57);
* System.out.println(s.toString());
*/
#Override
public String toString() {
return "First Name: " + firstName + ", Last Name: " + lastName + ", Age: " + age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The Things to take away from this.
1) Capitalize the first letter of class names! (Student)
2) note the class variables are private (look here for a tutorial Java Class Accessibility) and have getters and setter to control access outside the class.
3) I dont say "getName()" and return name and age. This doesnt make sense. Instead i make it so when you go toString() it shows all the relevant information.
4) Java is an object oriented language which means the classes that model data are supposed (to some extent) model appropriately to the way they are used in real life. This makes it more intuitive to people reading your code.
5) if your Group class (note the capital!) needs to contain many Students use a LIST such as an ArrayList. Arrays would make no sense because you dont know how many Students are going to be in each Group. A SET like i used above is similar to a list but only allows ONE of each item. For simplicity use a list though
6) the THIS operator refers to class (object) variables. In the constructor this.firstName refers to the firstName within the Class (object...an instance of the class) whereas just firstName would refer to the variable in the contructor and not alter the class variable.
use the constructor for that
class group {
String fname,lname;
group(String fname ){
this.fname=fname;
}
group(String fname,String lname){
this.fname=fname;
this.lname=lname;
}
group(String fname,String lname,int age){
this.fname=fname;
this.lname=lname;
this.age=age;
}
public String getName(){
return fname+lname+age;
}
}

Categories

Resources