1

我有一个任务是从 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]);
    }
}

}
4

1 回答 1

1

I believe that the following code solves the problem correctly and demonstrates the use of tail recursion, which sounded like the goal of the exercise. Also note that I'm making use of the various items in the Collection library rather than just using raw arrays and large if/then/else blocks.


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());
    }
}
于 2013-11-05T19:21:55.670 回答