my dog learned polymorphism
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to avoid null pointer exception" Watch "how to avoid null pointer exception" New topic

how to avoid null pointer exception

Rishi Singh
Ranch Hand

Joined: Dec 09, 2000
Posts: 321
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 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.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;

token[i] = stk.nextToken();
if(token[i]==" " | | token[i]==null)

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


StringBuffer sb1 = new StringBuffer(token[3]);
StringBuffer sb2 = new StringBuffer(token[0]);

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

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

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

//display elements
Map.Entry me = (Map.Entry);

Jim Yingst

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
I agree. Here's the link:
subject: how to avoid null pointer exception
It's not a secret anymore!