简体   繁体   中英

Phone number to letter combination with recursive approach throwing a Null Pointer Exception

First of all, I'm trying build a program that print out all the possible letter combination based on the a phone number input.

My problem is that i cannot get my recursion function to work, I'm getting the follow error stack. The error is pointing to line 46 which is " recursion("", line); and line 65 which is for (int i = 0; i < letters.length(); i++) {

Exception in thread "main" java.lang.NullPointerException
    at JPMorgan.test.PhoneNumberCombo.recursion(PhoneNumberCombo.java:46)
    at JPMorgan.test.PhoneNumberCombo.main(PhoneNumberCombo.java:65)

This is my code:

import org.apache.commons.io.IOUtils;

public class PhoneNumberCombo {


          static void recursion(String combination, String next_digits) {

                List<String> result = new ArrayList<String>();

                Map<String, String> phone = new HashMap<String, String>() {{
                    put("2", "abc");
                    put("3", "def");
                    put("4", "ghi");
                    put("5", "jkl");
                    put("6", "mno");
                    put("7", "pqrs");
                    put("8", "tuv");
                    put("9", "wxyz");
                  }};

                // BASE CASE no more digits found
                if (next_digits.length() == 0) {

                     // the combination is built
                    result.add(combination);
                    System.out.println(result);
                }

                else {

                  String digit = next_digits.substring(0, 1);
                  String letters = phone.get(digit);

                  for (int i = 0; i < letters.length(); i++) {
                    String letter = phone.get(digit).substring(i, i + 1);

                  recursion(combination + letter, next_digits.substring(1));
                }
            }

      }


      public static void main(String[] args) throws IOException {

            InputStream phoneInputStream = IOUtils.toInputStream("123456", "UTF-8");

            InputStreamReader reader = new InputStreamReader(phoneInputStream);
            BufferedReader in = new BufferedReader(reader);
            String line = in.readLine();

            if (line.length() != 0)
                recursion("", line);  

      }
}

Obviously the failing line indicates that letters is null . For example, this will happen for "0" or "1" , which are not present in your phone map, or for any other String .

You have to handle case where letters is null right after String letters = phone.get(digit) . Whether to skip this String or throw an explicit exception about non-appropriate symbol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM