卡在java电话号码字生成器上

时间:2013-11-05 15:59:39

标签: java phone-number

我有一项任务,可以从7位数的电话号码中生成每个可能的单词,并使用PrintWriter将其保存为.txt文件。我的代码在下面,但我的输出(目前只是打印到控制台)是相同的3“字”2187次。

package ks2_Lab19;

import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileNotFoundException;

public class WordGenerator {

private static String[] two = {"a", "b", "c"};
private static String[] three = {"d", "e", "f"};
private static String[] four = {"g", "h", "i"};
private static String[] five = {"j", "k", "l"};
private static String[] six = {"m", "n", "o"};
private static String[] seven = {"p", "r", "s"};
private static String[] eight = {"t", "u", "v"};
private static String[] nine = {"w", "x", "y"};
private static char[] numArray;
private static String[] wordList = new String[2187];

public static void convert(char[] input){
    for (int i = 0; i < 2184; i = i + 3){
        for (int a = 0; a < 7; a++){
            for (int b = 0; b < 3; b++){
                if (input[a] == '1' || input[a] == '0') {
                    wordList[i+b] = wordList[i+b] + " "; 
                }//if 0 or 1
                if (input[a] == '2'){
                    wordList[i+b] = wordList[i+b] + two[b];
                }//if 2
                if (input[a] == '3'){
                    wordList[i+b] = wordList[i+b] + three[b];
                }//if 3
                if (input[a] == '4'){
                    wordList[i+b] = wordList[i+b] + four[b];
                }//if 4
                if (input[a] == '5'){
                    wordList[i+b] = wordList[i+b] + five[b];
                }//if 5
                if (input[a] == '6'){
                    wordList[i+b] = wordList[i+b] + six[b];
                }//if 6
                if (input[a] == '7'){
                    wordList[i+b] = wordList[i+b] + seven[b];
                }//if 7
                if (input[a] == '8'){
                    wordList[i+b] = wordList[i+b] + eight[b];
                }//if 8
                if (input[a] == '9'){
                    wordList[i+b] = wordList[i+b] + nine[b];
                }//if 9
            }//possible output for loop
        }//input array for loop
    }//write to wordList for loop
}

public static void main(String[] args) {

    //initialize output file name and PrintWriter object
    String fileName = "output.txt";
    PrintWriter outputStream = null;
    String output = "";

    //try and catch exception
    try {
        outputStream = new PrintWriter(fileName);
    }
    catch (FileNotFoundException e){
        System.out.println("Error opening file " + fileName + ".");
        System.exit(0);
    }

    //initialize scanner and wordList array
    Scanner kb = new Scanner(System.in);
    for (int i=0; i < 2187; i++){
        wordList[i] = "";
    }

    //announce and accept input
    System.out.println("Please input a 7 digit phone number without special characters.");
    String num = kb.next();
    numArray = num.toCharArray();
    convert(numArray);
    for (int p = 0; p < 2187; p++){
        System.out.println(wordList[p]);
    }
}

}

1 个答案:

答案 0 :(得分:1)

我相信下面的代码正确地解决了问题并演示了尾递归的使用,这听起来像练习的目标。另请注意,我正在使用Collection库中的各种项目,而不是仅使用原始数组和大型if / then / else块。


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WordGenerator {

    private static Map<Character, char[]> digitMap;
    static {
        digitMap = new HashMap<Character, char[]>();

        digitMap.put(Character.valueOf('0'), new char[] { ' ' });
        digitMap.put(Character.valueOf('1'), new char[] { ' ' });
        digitMap.put(Character.valueOf('2'), new char[] { 'a', 'b', 'c' });
        digitMap.put(Character.valueOf('3'), new char[] { 'd', 'e', 'f' });
        digitMap.put(Character.valueOf('4'), new char[] { 'g', 'h', 'i' });
        digitMap.put(Character.valueOf('5'), new char[] { 'j', 'k', 'l' });
        digitMap.put(Character.valueOf('6'), new char[] { 'm', 'n', 'o' });
        digitMap.put(Character.valueOf('7'), new char[] { 'p', 'r', 's' });
        digitMap.put(Character.valueOf('8'), new char[] { 't', 'u', 'v' });
        digitMap.put(Character.valueOf('9'), new char[] { 'w', 'x', 'y' });
    }

    public static void convert(String input, String resultSoFar, List<String> allResults) {

        if (input.length() == 0) {
            // We have hit the end of the input phone number and thus the end of
            // recursion
            allResults.add(resultSoFar);
        } else {
            // Strip the next character off the front of the phone number
            Character nextDigit = Character.valueOf(input.charAt(0));

            // Look up the list of mappings from that digit to all letters
            char[] mappingArray = digitMap.get(nextDigit);

            // More robust error handling would throw an exception or do
            // something else when an unknown character was encountered in the
            // phone number.
            if (mappingArray != null) {

                // We have processed the first digit in the rest of the number,
                // so recurse with the rest of the number
                String inputTail = input.substring(1);

                // By iterating through the array the mapping lists do not all
                // have to be the same size.
                for (char nextLetter : mappingArray) {
                    // Put the next mapped letter on the end of the result being
                    // built and recurse
                    convert(inputTail, resultSoFar + nextLetter, allResults);
                }
            }
        }

    }
    public static void main(String[] args) {

        // Simplified version that does not ask for input
        String num = "8675309";
        List<String> results = new ArrayList<String>();

        // Starting condition is that the entire input needs to be processed,
        // the result so far is empty, and we have nothing in the list of final
        // answers
        convert(num, "", results);

        for (String nextResult : results) {
            System.out.println(nextResult);
        }

        System.out.println("End of results list. Total words generated: " + results.size());
    }
}