Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes arrays & sorting arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "arrays & sorting arrays" Watch "arrays & sorting arrays" New topic

arrays & sorting arrays

kieran pattni
Ranch Hand

Joined: Jan 19, 2004
Posts: 47
hi..i seem to be having problem making array seach work..i have phone book.. there is a search which would find the name and print name also phone works for first name seach but not the others..thanks in advance..

public class phoneDetails
String name;
String phoneNum;

public String getName() {return name;}

public String getPhoneNum() {return phoneNum;}

public void setName(String n ) { name = n;}

public void setPhoneNum(String pn) {phoneNum = pn;}

phoneDetails() {} // default constructor

phoneDetails(String n, String pn)
name = n;
phoneNum = pn;

public class phoneDemo
public static void main(String[]args)

phoneDetails [] phoneBook = new phoneDetails [4];

phoneBook[0] = new phoneDetails ("sarah connor", "0116-325637");
phoneBook[1] = new phoneDetails ("john smith", "0033-3444530");
phoneBook[2] = new phoneDetails ("will green", "7778-876896");
phoneBook[3] = new phoneDetails ("fire starter", "9111-999999");

for(int i = 0; i < phoneBook.length;i++)
System.out.println(phoneBook[i].getName() +"\t" +

int loc = Search.linearSearch(phoneBook, "will green");

if (loc != -1)
System.out.println(phoneBook[loc].name + "\t"+
phoneBook[loc ].phoneNum);
System.out.println("Not found");


class Search
// define method as static method; we can access it without
// creating an object of this class

// set to -1 for failed search

public static int linearSearch(phoneDetails [] arr, String name)
int location = -1;
for(int i = 0; i < arr.length;i++)
if (arr[i].name.equals(name)) // use equals() method to compare
// two string objects
// if true, store location
location = i;
return location;
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

The "break" statement near the end of the program is always executed. You need to add a set of braces around the statements that are to be controlled by the "if".

[Jess in Action][AskingGoodQuestions]
kieran pattni
Ranch Hand

Joined: Jan 19, 2004
Posts: 47
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
When posting code, please be sure to surround the code with the [code] and [/code] UBB Tags. This will help to preserve the formatting of the code, thus making it easier to read and understand.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: arrays & sorting arrays
jQuery in Action, 3rd edition