This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Are my tools buggy or are these programs significantly different? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Are my tools buggy or are these programs significantly different?" Watch "Are my tools buggy or are these programs significantly different?" New topic
Author

Are my tools buggy or are these programs significantly different?

Jamie
Greenhorn

Joined: Jan 15, 2000
Posts: 10
Pasted below are two simple phonebook applications that search for a name, then print the name and number.
I've inspected both of these programs, and they appear identical up to the if-else branches in the last dozen or so lines. Both are supposed to print all of the phonebook entries with the target last name when no first name is entered.
If I compile the first program, then run it right away, it runs perfectly. If I then compile and run the second program, it prints the correct entries when no first name is entered, then throws a Null Pointer Exception at PhoneBook.print. Here's the weirdest part: If I then run the first program again, it behaves like the second one -- until I recompile it and run it again, in which case it runs perfectly again.
I'm compiling the programs with javac in the JDK 1.2.2 and running them in the MS-DOS window that comes with Windows 95. Any idea what's going on?
Should both programs run correctly?
Are the structures of the if-else statements at the ends of each program functionally equivalent?
FIRST PROGRAM:
import java.io.*;
class PhoneEntry
{
String lastname; // name of a person
String firstname;
String phone; // their phone number
PhoneEntry( String ln, String fn, String p )
{
lastname = ln.toUpperCase(); firstname = fn.toUpperCase(); phone = p;
}
}
class PhoneBook
{
PhoneEntry[] phoneBook;
PhoneBook() // constructor
{
phoneBook = new PhoneEntry[ 9 ] ;
phoneBook[0] = new PhoneEntry( "Barclay", "James", "(418) 665-1223" );
phoneBook[1] = new PhoneEntry( "Dunbar", "Grace", "(860) 399-3044" );
phoneBook[2] = new PhoneEntry( "Kratides", "Paul", "(815) 439-9271" );
phoneBook[3] = new PhoneEntry( "Smith", "Violet", "(312) 223-1937" );
phoneBook[4] = new PhoneEntry( "Wood", "John", "(913) 883-2874" );
phoneBook[5] = new PhoneEntry( "Barclay", "Bill", "(418) 555-1223" );
phoneBook[6] = new PhoneEntry( "Barclay", "Ted", "(418) 115-1223" );
phoneBook[7] = new PhoneEntry( "Smith", "Sarah", "(312) 555-1937" );
phoneBook[8] = new PhoneEntry( "Judd", "James", "(418) 665-1223" );

}
PhoneEntry flsearch( String targetLastName, String targetFirstName)
{
for ( int j=0; j < phoneBook.length; j++ )
{
if ( phoneBook[ j ].lastname.equals( targetLastName ) && phoneBook[ j ].firstname.equals( targetFirstName ))
return phoneBook[ j ];
}
return null;
}

PhoneEntry lsearch( String targetLastName)
{
for ( int j=0; j < phoneBook.length; j++ )
{
if ( phoneBook[ j ].lastname.equals( targetLastName ) )
return phoneBook[ j ];
}
return null;
}
void print( String targetLastName)
{
for (int j=0; j < phoneBook.length; j++)
{
if ( phoneBook[ j ].lastname.equals( targetLastName ) )
{
System.out.print( phoneBook[j].lastname + " " +phoneBook[j].firstname + " " +phoneBook[j].phone); System.out.println( );
}
}
}
}
class pb20
{
public static void main ( String[] args ) throws IOException
{
BufferedReader bf = new BufferedReader (new InputStreamReader (System.in));

PhoneBook pb = new PhoneBook();
String inData;
String searchLastname = "Wokloy";
String searchFirstname = "Wokloy";

boolean cont;
cont = true;
while (cont)
{
//ask for input
System.out.println("Enter last name");
inData = bf.readLine();
searchLastname = inData.toUpperCase();

if (searchLastname.equals("QUIT"))
{
System.out.println("Goodbye" );
cont = false;
}
else
{
// search for searchname
PhoneEntry entry;
System.out.println("Enter first name");
inData = bf.readLine();

if (inData.length() != 0)
{
searchFirstname = inData.toUpperCase();
entry = pb.flsearch( searchLastname, searchFirstname );
if ( entry == null )
System.out.println("Name not found. Try anew." );
else
System.out.println( entry.lastname +" " +entry.firstname + ": " + entry.phone );
}
else
pb.print(searchLastname);

}

}
}
}
SECOND PROGRAM:
import java.io.*;
class PhoneEntry
{
String lastname; // name of a person
String firstname;
String phone; // their phone number
PhoneEntry( String ln, String fn, String p )
{
lastname = ln.toUpperCase(); firstname = fn.toUpperCase(); phone = p;
}
}
class PhoneBook
{
PhoneEntry[] phoneBook;
PhoneBook() // constructor
{
phoneBook = new PhoneEntry[ 11 ] ;
phoneBook[0] = new PhoneEntry( "Barclay", "James", "(418) 665-1223" );
phoneBook[1] = new PhoneEntry( "Dunbar", "Grace", "(860) 399-3044" );
phoneBook[2] = new PhoneEntry( "Kratides", "Paul", "(815) 439-9271" );
phoneBook[3] = new PhoneEntry( "Smith", "Violet", "(312) 223-1937" );
phoneBook[4] = new PhoneEntry( "Wood", "John", "(913) 883-2874" );
phoneBook[5] = new PhoneEntry( "Barclay", "Bill", "(418) 555-1223" );
phoneBook[6] = new PhoneEntry( "Barclay", "Ted", "(418) 115-1223" );
phoneBook[7] = new PhoneEntry( "Smith", "Sarah", "(312) 555-1937" );
phoneBook[8] = new PhoneEntry( "Judd", "James", "(418) 665-1223" );

}
PhoneEntry flsearch( String targetLastName, String targetFirstName)
{
for ( int j=0; j < phoneBook.length; j++ )
{
if ( phoneBook[ j ].lastname.equals( targetLastName ) && phoneBook[ j ].firstname.equals( targetFirstName ))
return phoneBook[ j ];
}
return null;
}

PhoneEntry lsearch( String targetLastName)
{
for ( int j=0; j < phoneBook.length; j++ )
{
if ( phoneBook[ j ].lastname.equals( targetLastName ) )
return phoneBook[ j ];
}
return null;
}
void print( String targetLastName)
{
for (int j=0; j < phoneBook.length; j++)
{
if ( phoneBook[ j ].lastname.equals( targetLastName ) )
{
System.out.print( phoneBook[j].lastname + " " +phoneBook[j].firstname + " " +phoneBook[j].phone);

System.out.println( );
}
}
}
}
class pbfirlasalmost // this throws a NPE if no first name or wrong one entered
{
public static void main ( String[] args ) throws IOException
{
BufferedReader bf = new BufferedReader (new InputStreamReader (System.in));

PhoneBook pb = new PhoneBook();
String inData;
String searchLastname = "Wokloy";
String searchFirstname = "Wokloy";

boolean cont;
cont = true;
while (cont)
{
//ask for input
System.out.println("Enter last name");
inData = bf.readLine();
searchLastname = inData.toUpperCase();

if (searchLastname.equals("QUIT"))
{
System.out.println("Goodbye" );
cont = false;
}
else
{
// search for searchname
PhoneEntry entry;
System.out.println("Enter first name");
inData = bf.readLine();

if (inData.length() == 0)
{
pb.print(searchLastname);
}
else
{
searchFirstname = inData.toUpperCase();
entry = pb.flsearch( searchLastname, searchFirstname );
if ( entry == null )
System.out.println("Name not found. Try anew." );
else
System.out.println( entry.lastname +" " +entry.firstname + ": " + entry.phone );
}

}

}
}
}

paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20270
    ∞

This was huge.
I just browsed the second example.
It looks like your comparisons use .equals() but the stuff you send in converts everything to upper case. I think that would make sure that you get no matches. Could that be the problem?

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Jamie
Greenhorn

Joined: Jan 15, 2000
Posts: 10
Sorry about the length of the previous post. My comments preceding the code tried to direct attention to the last few lines of each program, but since I can't find what's causing the second program to fail while the first runs, I thought I'd better include the entirety of both, in case I missed something on an earlier line. I realize it would take quite a lot of curiosity for someone to pore over the whole.
I don't think the problem is related to the conversion to uppercase. Everything gets converted, and I do get matches whenever I search for a name that's on the list. Even when I search just for last name matches, the second program finds them and prints them, but then it throws a Null Pointer Exception.
Are there bugs in the JDK 1.2.2 compiler or the MS-DOS window that could cause the following? The first program ran perfectly, then, without my changing it, failed exactly the same test, then ran perfectly again after being recompiled from the same source file
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
OK. There are several issues with this code.
First. To calm you down, there is no wierdness with your tools. What you are seeing (and it did it to me too when I tried it) is a deliberate part of Java! What has happened is that you have compiled your second "program" after your first "program". As you have some classes with similar names, their ".class" files have overwritten the previous working version with the new buggy version.
Let this be the first lesson for you. Always (and I mean always) put one class per source file. That way you know exactly where any given class file came from. It would also have cut doen the size of your post here!
Now on to why it is throwing an exception. It's simple. In the second file you have the line
phoneBook = new PhoneEntry[ 11 ];
And then fill it with only 9 entries. When your later code searches using
for ( int j=0; j < phoneBook.length; j++ )
It tries to read the 10th element of the array, but it is still null.
Let this be the second lesson for you. Always (and I mean always) use direct initialisation syntax, particularly for arrays, but also for any other variables. ie:

If you use this syntax, you can add and remove elements from the definition, without ever having to worry about the number of entries.
While we're on the subject of initialisations, I'd also be very tempted to change the likes of:

to just

and move the definitions of

to inside the "while" loop where they are used.
I hope this helps.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Jamie
Greenhorn

Joined: Jan 15, 2000
Posts: 10
Thank you, Frank, both for spotting the specific problem and for providing several important lessons that will save me much confusion from now on.
I'll try to keep any future postings shorter, and I can see how keeping source files separate will help to focus the search for bugs into a smaller chunk of code.
I've been teaching myself Java for around six weeks, using mostly a couple of free tutorials I've found online. This is my first experience with programming. I do seem to be picking up a few bad habits. Can you recommend an online course or tutorial, or a traditional textbook? The ideal learning tool for me would provide lots of programming exercises and answers to perhaps half of them, much like many math texts.
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20270
    ∞

Have you looked at the Cattle Drive here? The idea is that you do eight small assignments, e-mail them to me and I tell you what you need to change.
Check out http://www.javaranch.com/drive/index.html
The big idea is that I force my style and habits on you as well as teach you about the basic constructs of java.
As for a book, go to www.javaranch.com/books.html and read about "Just Java". This book makes the hardest java stuff seem simple.
[This message has been edited by Paul Wheaton (edited January 21, 2000).]
Jamie
Greenhorn

Joined: Jan 15, 2000
Posts: 10
Thanks, Paul. Those exercises look like fun, and I'd like to participate.
Two questions about the required book:
I went to Amazon and read the reviews. Most of them say that the book is intended for intermediate programmers, especially with a background in C. Do you agree?
The author's description mentions that the CD includes compilers for a dozen other languages. Does it include a decent C and C++ compiler?
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20270
    ∞

I think people who are new to programming in general will have no problem with the book. In fact, I can't think of a better book for people that are new to programming. I think the reason people said what they did is that the book is called "Just Java" - perhaps implying to them that it excludes anything that java may have in common with other languages. Not true.
As for other stuff on the CD - there is certainly a lot there. I've looked mostly at the non computer stuff.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Are my tools buggy or are these programs significantly different?
 
Similar Threads
Please Help me debug program
Casting Problem *Help Please
String and Numeric Parameters
Why does this"if" statement get skipped?
Question for Frank Carver