more more and more improvement
i posted my question yesterday.
http://forum.java.sun.com/thread.jspa?threadID=5123570&messageID=9434977#9434977
Now i would like to improve my program more. i will give user an option to add an entry, delete an entry, search an entry. The author never told us about any of these functions. by doing my research i came to know that arraylist would be my better option but i have no clue about arraylist. my question is there any way i can add 3 of these methods in my program? if i can then can i get a little explanation how can i be able to do all these 3 functions? any help will be really appreciated. this is my program for the time being. after i get responses i will update my code.
/*
* PhoneBookTester.java
*
* Created on January 11, 2007, 8:13 PM
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
/**
*
* @author chris
*/
import java.util.Scanner;
class PhoneEntry
{
String firstName;
String lastName;// name of a person
String phone;// their phone number
PhoneEntry( String f, String l, String p ){
firstName = f; lastName = l; phone = p;
}
}
class PhoneBook{
PhoneEntry[] phoneBook;
PhoneBook()// constructor
{
phoneBook =new PhoneEntry[ 7 ] ;
phoneBook[0] =new PhoneEntry(
"James ","Barclay ","(418)665-1223");
phoneBook[1] =new PhoneEntry(
"Grace" ,"Dunbar","(860)399-3044");
phoneBook[2] =new PhoneEntry(
"Paul","Kratides","(815)439-9271");
phoneBook[3] =new PhoneEntry(
"Violet" ,"Smith","(312)223-1937");
phoneBook[4] =new PhoneEntry(
"John","Smith","(913)883-2874");
phoneBook[5] =new PhoneEntry(
"Suleman","Smith","(913)883-2874");
phoneBook[6] =new PhoneEntry(
"Violet","Dunbar","(913)883-2874");
}
PhoneEntry search( String lastName, String firstName){
for (int j=0; j<phoneBook.length; j++){
if ( phoneBook[ j ].lastName.equals( lastName) && phoneBook[ j ].firstName.equals( firstName))
return phoneBook[ j ];
}
returnnull;
}
public PhoneEntry[] search1( String lName){
int count=0;
for(int j=0; j><phoneBook.length; j++){
if ( phoneBook[ j ].lastName.equals(lName)) count++;
}
if(count>0){
int k=0;
PhoneEntry pe[]=new PhoneEntry[count];
for(int j=0; j<phoneBook.length; j++){
if ( phoneBook[ j ].lastName.equals(lName))
pe[k++]=phoneBook[j];
}
return pe;
}
returnnull;
}
}
class PhoneBookTester{
publicstaticvoid main (String[] args){
String firstName="";
String lastName="";
PhoneBook pb =new PhoneBook();
Scanner scan =new Scanner(System.in);
do{
System.out.println("Enter the last name or enter quit to terminate" );
lastName = scan.nextLine();
if(lastName.equals("quit"))break;
System.out.println("Enter the first name ");
firstName = scan.nextLine();
PhoneEntry entry =pb.search( lastName, firstName );
PhoneEntry[] entry1 = pb.search1(lastName);
if(entry1.length==0){
System.out.println("No Match Found for :-both the entries -of -first & last names..");
}else{
for(int i=0;i<entry1.length;i++){
System.out.println( entry1[i].firstName +" "+entry1[i].phone);
}
}
if ( entry !=null ) System.out.println("The number is (of the entry matching both first & last name) " +entry.phone );
else
System.out.println("Name not found");
}while(true);
System.out.println("Good Bye ");
}
}
Message was edited by:
fastmike>
[7415 byte] By [
fastmikea] at [2007-11-26 14:54:05]

How about doing a little more research and see what the Java Collections Tutorial can teach you, then come back with questions if you need to?
http://java.sun.com/docs/books/tutorial/collections/index.html
The Collections Tutorial has example code and samples sprinkled throughout. Here's the link to the portion that discusses LIst and related classes, like ArrayList:
http://java.sun.com/docs/books/tutorial/collections/interfaces/list.html
A glance at the javadocs for java.util.List should give you all you need, Mike:
package cruft;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
* User: Michael
* Date: Jan 11, 2007
* Time: 9:47:03 PM
* To change this template use File | Settings | File Templates.
*/
public class PhoneBook implements Serializable
{
private List<PhoneBookEntry> directory;
public static void main(String[] args)
{
PhoneBookEntry [] entries =
{
new PhoneBookEntry("foo", "111-2222"),
new PhoneBookEntry("bar", "333-4444"),
new PhoneBookEntry("baz", "555-6666"),
};
PhoneBook phoneBook = new PhoneBook(Arrays.asList(entries));
System.out.println(phoneBook);
phoneBook.add(new PhoneBookEntry("fastmike", "777-8888"));
System.out.println(phoneBook);
phoneBook.remove(entries[0]);
System.out.println(phoneBook);
PhoneBookEntry search = phoneBook.findByName("baz");
System.out.println(search);
}
public PhoneBook(List<PhoneBookEntry> directory)
{
this.directory = new ArrayList<PhoneBookEntry>(directory);
}
public void add(PhoneBookEntry entry)
{
directory.add(entry);
}
public void remove(PhoneBookEntry entry)
{
directory.remove(entry);
}
public PhoneBookEntry findByName(String name)
{
PhoneBookEntry value = null;
for (PhoneBookEntry entry : directory)
{
if (entry.getName().equals(name))
{
value = entry;
break;
}
}
return value;
}
public String toString()
{
return new StringBuilder().append("PhoneBook{").append("directory=").append(directory).append('}').toString();
}
}
class PhoneBookEntry implements Serializable
{
private String name;
private String number;
public PhoneBookEntry(String name, String number)
{
this.name = name;
this.number = number;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
PhoneBookEntry that = (PhoneBookEntry) o;
if (name != null ? !name.equals(that.name) : that.name != null)
{
return false;
}
if (number != null ? !number.equals(that.number) : that.number != null)
{
return false;
}
return true;
}
public int hashCode()
{
int result;
result = (name != null ? name.hashCode() : 0);
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}
public String toString()
{
return new StringBuilder().append("PhoneBookEntry{").append("name='").append(name).append('\'').append(", number='").append(number).append('\'').append('}').toString();
}
}
%
Got it.Chuck but the tutorial which i am doing the author just taught us about linear search and in the exercise set problems he said to add new methods which includes, adding a data, deleting a data and searching a data. and the tutorial which you give me all includes searching algorithm like queue, or arraylist and List. which i am totally not familiar with.is there any other way to do add, searcxh or delete instead of using the algorithms and tutorial you posted? cause if not then i guess probably i will leave alone since i have no clue what this means.
public class extends(future chapter not rite now ).
i was thinking of creating a function something like this.
public void add(String firstName, String lastName, String phone)
dont know if this is rite or not and still thinking of how a specific array can be deleted.
Message was edited by:
fastmike
Thanks duffy for a great example. i will look at java.util.list docs to see if i can be able to figure this thing out. and i really appreciate for a great example gives me a little idea. Thanks
> Thanks duffy for a great example. i will look at> java.util.list docs to see if i can be able to figure> this thing out. and i really appreciate for a great> example gives me a little idea. A little idea? It's the whole bloody
> Got it.Chuck but the tutorial which i am doing the> author just taught us about linear search What's linear search got to do with it? Iterate through the collection until you get a match. It's O(n).%
a good idea. i am reading the docs rite now. looks like i had to use java.util.list in order to add and delete. But thats messed up. i am disappointed that author should give us an idea about list before giving that exercise problem. instead i got an example from you(which is great and which is advance :). it took me like 4 hrs yesterday just to complete my program which i have posted and which i have posted a question yesterday in the forums also. now looks like this **** thing is also going to take a lot of time since i need to see how the java.util.list works.
> > Got it.Chuck but the tutorial which i am doing the
> > author just taught us about linear search
>
> What's linear search got to do with it? Iterate
> through the collection until you get a match. It's
> O(n).
>
> %
Very true. Linear search just basically search through the array and will display if the search is found but can't do adding and deleting and all that stuff. definitely java.util.list is my only option.
so i read the api documentation. here is what i came up with my add function. but it is giving me error.
i want to check if there is a space to add in my array and if it is not null then create a PhoneEntry object and assign its reference to that cell.here is my code but it is giving me error.
public void add (int index, PhoneEntry element) {
String[] count= new String[phoneBook.length];
if(phoneBook.length!=null)
for(int j=0; j<phoneBook.length; j++) {
PhoneEntry pd[] = new PhoneEntry[count];
count[j] = phoneBook[j];
}
}
here are the errors.
C:\Java programs\PhoneBookTester.java:68: incompatible types
found: java.lang.String[]
required: int
PhoneEntry pd[] = new PhoneEntry[count];
^
C:\Java programs\PhoneBookTester.java:69: incompatible types
found: PhoneEntry
required: java.lang.String
count[j] = phoneBook[j];
^
3 errors
>
> so i read the api documentation. here is what i came
> up with my add function. but it is giving me error.
> i want to check if there is a space to add in my
> array and if it is not null then create a PhoneEntry
> object and assign its reference to that cell.here is
> my code but it is giving me error.
> > public void add (int index, PhoneEntry element) {
>String[] count= new String[phoneBook.length];
> if(phoneBook.length!=null)
>
>for(int j=0; j<phoneBook.length; j++) {
>PhoneEntry pd[] = new PhoneEntry[count];
>count[j] = phoneBook[j];
> }
>
> }
>
> here are the errors.
> > C:\Java programs\PhoneBookTester.java:68:
> incompatible types
> found: java.lang.String[]
> required: int
> PhoneEntry pd[] = new PhoneEntry[count];
> ^
> java:69: incompatible types
> found: PhoneEntry
> required: java.lang.String
>count[j] = phoneBook[j];
> ^
Wake up lad!
For the first one
PhoneEntry pd[] = new PhoneEntry[count.length];
For the second you have an array of Strings and an array of PhoneEntry-s . A PhoneEntry is not a String so not sure what you are expecting there.
I also think that inside your for loop is a very odd place to be initializing an array. (Hint: It is more than odd it is wrong)
>Wake up lad!
lol i am trying to.
I guess i am going to leave it alone until i google and find some good examples of using java.util.List. i put alot of time and effort just to complete the last exercise. I will move on and will come back to this problem as soon i get an idea of adding and deleting. unless someone has time to just give me an explanation like you and Captain give me yesterday on completing the methods i need from my previous exercise.
Thanks
Message was edited by:
fastmike
duffy the example you posted was basically inserting data manually not by the user input. i stuided your example but you have used pure OO language which is hard for me to understand. some of the operators like private List<PhoneBookEntry> directory;
dont have no clue what <> means. what i really meant to say was how can i add a method in which the user will have an option to add the firstanem, lastname and phone. secondly i have an array length of 7. so if the data is manually inserted by the user by typing the name, etc then how can i increase the size of my array? when i try to increase the length of my array instead of 7 i typed 20 it works but when i run my program it gives me an error though my entries in array still exist. new code for user intereaction.
import java.util.Scanner;
import java.util.List;
class PhoneEntry
{
String firstName;
String lastName;// name of a person
String phone;// their phone number
PhoneEntry( String f, String l, String p ){
firstName = f; lastName = l; phone = p;
}
}
class PhoneBook{
PhoneEntry[] phoneBook;
PhoneBook()// constructor
{
phoneBook = new PhoneEntry[7 ] ;
phoneBook[0] = new PhoneEntry(
"James ", "Barclay ", "(418)665-1223");
phoneBook[1] = new PhoneEntry(
"Grace" , "Dunbar", "(860)399-3044");
phoneBook[2] = new PhoneEntry(
"Paul", "Kratides", "(815)439-9271");
phoneBook[3] = new PhoneEntry(
"Violet" , "Smith", "(312)223-1937");
phoneBook[4] = new PhoneEntry(
"John", "Smith", "(913)883-2874");
phoneBook[5] = new PhoneEntry(
"Suleman", "Smith", "(913)883-2874");
phoneBook[6] = new PhoneEntry(
"Violet", "Dunbar", "(913)883-2874");
}
PhoneEntry search( String lastName, String firstName){
for (int j=0; j<phoneBook.length; j++){
/* Here you compared only the last name
not the first name ?!!-i have changed
*/
if ( phoneBook[ j ].lastName.equals( lastName) && phoneBook[ j ].firstName.equals( firstName))
return phoneBook[ j ];
}
return null;
}
public PhoneEntry[] search1( String lName){
/*Remember here you have to return an array of values not a single value
if there exists more than one value*/
int count=0;
for(int j=0; j><phoneBook.length; j++) {
if ( phoneBook[ j ].lastName.equals(lName)) count++;
}
if(count>0){
int k=0;
PhoneEntry pe[]=new PhoneEntry[count];
for(int j=0; j<phoneBook.length; j++) {
if ( phoneBook[ j ].lastName.equals(lName))
pe[k++]=phoneBook[j];
}
return pe;
}
return null;
}
/* public void add (PhoneEntry, index) {
if(phoneBook.length!=null)
for(int j=0; j><phoneBook.length; j++) {
count[j] = phoneBook[j];
}
} */
}
class PhoneBookTester1{
public static void main (String[] args){
String firstName;
String lastName;
String choice;
PhoneBook pb = new PhoneBook();
Scanner scan = new Scanner(System.in);
System.out.println("Which one of the following would you like to do ");
System.out.println("1. View the PhoneBook ?");
System.out.println( "2. Add an entry in the phoneBook" );
System.out.println( "3. delete a phonebook");
System.out.println("Enter your choice: ");
choice = scan.nextLine();
if(choice.equals("1")){
System.out.println("Enter the last name ");
lastName = scan.nextLine();
System.out.println("Enter the first name ");
firstName = scan.nextLine();
PhoneEntry entry = pb.search(lastName, firstName);
PhoneEntry[] entry1 = pb.search1(lastName);
if(entry1.length==0) {
System.out.println("name cannot be found");
} else {
for(int j=0; j><entry1.length; j++)
System.out.println(entry[j].firstName + " " + entry[j].phone);
}
}
}
}
i have added some user intereaction by creating a menu what a user wants to do but still lacking in the add and delete method. anyone willing to help will be really appreciated.
and yes one more thing you see this statement :
class PhoneBook{
PhoneEntry[] phoneBook;
PhoneBook()// constructor
{
phoneBook = new PhoneEntry[7 ] ;
phoneBook[0] = new PhoneEntry(
"James ", "Barclay ", "(418)665-1223");
phoneBook[1] = new PhoneEntry(
"Grace" , "Dunbar", "(860)399-3044");
i have the length 7 and all the entries are manually entered by me not by the user so my question is even if i am successful in creating an add method how will the add method will be able to store the new data entered by the user? if i change the length from 7 to 20 of my array (phonebook) it gives me an error.
Which one of the following would you like to do
1. View the PhoneBook ?
2. Add an entry in the phoneBook
3. delete a phonebook
Enter your choice:
1
Enter the last name
Smith
Enter the first name
Suleman
Exception in thread "main" java.lang.NullPointerException
at PhoneBook.search1(PhoneBookTester1.java:50)
at PhoneBookTester1.main(PhoneBookTester1.java:93)
Process completed.
>
> dont have no clue what <> means. http://java.sun.com/docs/books/tutorial/extra/generics/index.htmlIf you're going to work with Collections, you should know what Generics are. They aren't hard at all.
i dont want to learn about generics rite now my main aim is to complete the program not to learn about generics may be later on. any idea cap what can i do?
> any idea cap what can i do?You could create an [url= http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html]ArrayList[/url] that holds the PhoneEntries. It automagically adjusts to the correct size. If you use an ArrayList, I suggest you learn about generics, though.
Generics are easy. Instead of:
ArrayList al = new ArrayList();
You would use:
ArrayList<PhoneEntry> al = new ArrayList<PhoneEntry>();
The <PhoneEntry> part just means that the ArrayList should hold PhoneEntry objects.
> > any idea cap what can i do?
>
> You could create an
> [url=http://java.sun.com/j2se/1.5.0/docs/api/java/util
> /ArrayList.html]ArrayList[/url] that holds the
> PhoneEntries. It automagically adjusts to the
> correct size. If you use an ArrayList, I suggest you
> learn about generics, though.
i am pretty much sure there is another way to do it. anyways thanks alot once i find another way to do it i will post the code.
Thanks
You could create a whole new array everytime the user enters a new PhoneEntry, but that would be annoying.
public void add(PhoneEntry p)
{
PhoneEntry[] temp = new PhoneEntry[phoneBook.length+1];
//fill in values from phoneBook into temp, then add p
phoneBook = temp;
}
Wow. that is what i was really looking for. i know i need to learn about generics but i am pretty much sure the author is not that dumb to post a question in an exercise in which we have to use arraylist or generics. but arraylist is a future chapter so once i learn about arraylist i will redo this exercise agian. appreciated.
There's always another way to do it. Here's how it might look if you use an array instead of generics and List.It requires some special handling that List takes care of for you. - %
package cruft;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: Michael
* Date: Jan 11, 2007
* Time: 9:47:03 PM
* To change this template use File | Settings | File Templates.
*/
public class PhoneBook implements Serializable
{
private static final int DEFAULT_SIZE = 20;
private PhoneBookEntry [] directory;
private int nextEntryIndex;
private static final int DEFAULT_BUFFER_SIZE = 1024;
public static void main(String[] args)
{
PhoneBookEntry [] entries =
{
new PhoneBookEntry("foo", "111-2222"),
new PhoneBookEntry("bar", "333-4444"),
new PhoneBookEntry("baz", "555-6666"),
};
PhoneBook phoneBook = new PhoneBook(Arrays.asList(entries));
System.out.println(phoneBook);
phoneBook.add(new PhoneBookEntry("fastmike", "777-8888"));
System.out.println(phoneBook);
phoneBook.remove(entries[0]);
System.out.println(phoneBook);
PhoneBookEntry search = phoneBook.findByName("baz");
System.out.println(search);
}
public PhoneBook(List<PhoneBookEntry> directory)
{
int numEntries = Math.max(directory.size(), DEFAULT_SIZE);
this.directory = new PhoneBookEntry[numEntries];
for (PhoneBookEntry entry : directory)
{
this.directory[nextEntryIndex++] = entry;
}
}
public void add(PhoneBookEntry entry)
{
directory[nextEntryIndex++] = entry;
}
public void remove(PhoneBookEntry entry)
{
for (int i = 0; i < nextEntryIndex; ++i)
{
if (entry.equals(directory[i]))
{
directory[i] = null; // TODO: What do you do if you remove an entry from the middle of the array? NPE
}
}
}
public PhoneBookEntry findByName(String name)
{
PhoneBookEntry value = null;
for (int i = 0; i < nextEntryIndex; ++i)
{
if ((directory[i] != null) && (directory[i].getName().equals(name)))
{
value = directory[i];
break;
}
}
return value;
}
public String toString()
{
StringBuilder builder = new StringBuilder(DEFAULT_BUFFER_SIZE);
builder.append("PhoneBook{");
for (int i = 0; i < nextEntryIndex; ++i)
{
PhoneBookEntry entry = directory[i];
if (entry == null)
{
builder.append("null");
}
else
{
builder.append(entry.toString());
}
builder.append(",");
}
builder.append('}');
return builder.toString();
}
}
class PhoneBookEntry implements Serializable
{
private String name;
private String number;
public PhoneBookEntry(String name, String number)
{
this.name = name;
this.number = number;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
PhoneBookEntry that = (PhoneBookEntry) o;
if (name != null ? !name.equals(that.name) : that.name != null)
{
return false;
}
if (number != null ? !number.equals(that.number) : that.number != null)
{
return false;
}
return true;
}
public int hashCode()
{
int result;
result = (name != null ? name.hashCode() : 0);
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}
public String toString()
{
return new StringBuilder().append("PhoneBookEntry{").append("name='").append(name).append('\'').append(", number='").append(number).append('\'').append('}').toString();
}
}
Compare this implementation to the one I posted with List. There aren't many differences, are there? Most importantly, the public interface didn't change, just the private implementation.%
Man thanks alot for another example. yes not alot of difference. but wow you know some advance tricks of this Java language. i wish i was that much skillful. it will again take some time to understand your code but your add method and delete method was the one which i was concerned and i got an example now from you and captain and i will try to implement it and hopefully no definitely post the correct code :). **** dude you are clever. i am still struggling in defining methods and their return type though i have solved bunch of problems but you know its in my mind that i am not very comfortable yet hopefully in the future and the more forward i am moving in this java technology like using data structures, array, etc the more more more complex my mind is getting. and yes i am not those other kind of newbies who just wants the answer but i prefer explanation rather than getting answer because i am studying for myself not for my school. i am graduating this spring. i am learning mySql and Java at the same time dividing a little time between them. its just that mental block rite now. hope to get it over soon. oonce again Thanks alot duffy.
Message was edited by:
fastmike
The thing you need to be careful of is what happens when you add and remove, right? I cheated a bit, because if something was removed in the middle of the array I just set it to null. This might cause problems.
The solution is to expand and compress the entries when you add or remove, but I wanted to keep it simple for you.
This is the motivation for learning and using the java.util Collections. They handle that stuff for you.
%