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?
Code:// 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); } }




Reply With Quote