File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes how to avoid null pointer exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to avoid null pointer exception" Watch "how to avoid null pointer exception" New topic
Author

how to avoid null pointer exception

Rishi Singh
Ranch Hand

Joined: Dec 09, 2000
Posts: 321
hi,
I am reading lines from a file via a StringTokenizer,and trying to put it in a hashtable and then sort it as per some algo.If the file from where Iam reading contains a blankline it gives me a null pointer exception...how to I get rid of this
Rishi Singh
Ranch Hand

Joined: Dec 09, 2000
Posts: 321
here is the code for the above problems .... would like input for the same.
import java.io.*;
import java.util.*;
public class SortMultiField
{
public static void main(String args[]) throws IOException
{
String str;
String delim = "|";
BufferedReader br = new BufferedReader(new FileReader(args[0]));
//PrintWriter pw = new PrintWriter();
Map m = new TreeMap();
while((str = br.readLine()) != null )
{
StringTokenizer stk = new StringTokenizer(str, delim);
String token[] = new String[4];
int i = 0;
while(stk.hasMoreTokens())
{


token[i] = stk.nextToken();
//System.out.println(token[i]);
if(token[i]==" " | | token[i]==null)

//if(token[i]==" " | | token[i]==null)break;

i++;

}
StringBuffer sb1 = new StringBuffer(token[3]);
sb1.append("|"+token[2]);
StringBuffer sb2 = new StringBuffer(token[0]);
sb2.append("|"+token[1]);
/*System.out.println(sb1);
System.out.println(sb2);*/

m.put(sb1.toString(), sb2.toString());
}

//get set of entries
Set set = m.entrySet();

//set an iterator
Iterator it = set.iterator();

//display elements
while(it.hasNext())
{
Map.Entry me = (Map.Entry)it.next();
System.out.println(me.getKey().toString()+"|"+me.getValue().toString());
}

}
}
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I'm sure that when this failed, you got a nice big stack trace printed somewhere. What did it say? Most importantly in this case - exactly which line of your program did it say was the source of the error? This is really useful information, and you really can't be a good Java programmer without learning how to interpret a stack trace.


"I'm not back." - Bill Harding, Twister
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: how to avoid null pointer exception