PDA

Click to See Complete Forum and Search --> : null pointer Exception?


Dillinger4
Aug 19th, 2001, 04:05 PM
I keep getting a null pointer exception. If i uncomment the lines
// Object o = stringMap.put(key,charcount);
//System.out.println(o);
i get a null value. So how do i use the put method? Do i have to put then iteriate to the next element? or is it just like using the add method?



// create a method that takes a String as an arguement and returns a TreeMap
// which will map the string and the number of characters that occur only
// once within the string. since the counting operation can be
// time consuming, the method should cache
// the results so that when the method is
// given a string previously encountered,it will
// simply retrieve the stored result.

import java.io.*;
import java.util.*;

public class MultipleChar{
public static void main(String[] args){

for(;;){
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
try{
System.out.println("Please enter a string");
String key = buff.readLine();
TreeMap tm = (TreeMap) checkForDuplicates(key);

System.out.println("Within" + tm.get(key) + "there were" + "characters that only appeared once");
System.out.println("Press x if you would like to exit");
String exit = buff.readLine();
if(exit.equalsIgnoreCase("x")){System.exit(0);}
}catch(Exception e){System.err.println(e);}
}
}

public static Object checkForDuplicates(String key){
int onlyappearsonce = 0;
boolean charmatch = false;
Map stringMap = new TreeMap();


// check map to see if string is present, if it is return key

if(stringMap.containsKey(key)){return stringMap.get(key);}

// if string is not present
// calculate characters that only appear once and add to map

for(int index = 0; index <= key.length() - 1; ++index){
char matchingchar = key.charAt(index);

for(int x = 1 + index; x <= key.length() - x ; ++x){
if(matchingchar == key.charAt(x)){
charmatch = true;
break;
}
}
if(charmatch == false){++onlyappearsonce;}
}
Integer charcount = new Integer(onlyappearsonce);

// Object o = stringMap.put(key,charcount);
//System.out.println(o);
return stringMap.put(key,charcount);
}
}

crptcblade
Aug 19th, 2001, 05:30 PM
put() returns the value associated with the specified key. If ir returns null, then nothing was associated with that key.

So if you get null, then you are not replacing any values

:)

Dillinger4
Aug 19th, 2001, 06:52 PM
The put() method inserts a mapping ie. a <key value> pair, also called an entry.

The get() method returns the value to which the specified keyu is mapped or NULL if no mapping is found.

So maybe i have to put() first to add an entry to the Map then
i have to get() to retrieive it. Ill check it out.

Thanks.