Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to avoid null pointer exception

 
Rishi Singh
Ranch Hand
Posts: 321
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 321
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic