卡在java电话号码字生成器上 [英] stuck on a java phone number word generator

查看:148
本文介绍了卡在java电话号码字生成器上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an assignment to generate every possible word from a 7 digit phone number and use PrintWriter to save it as a .txt file. My code is below but my output (currently just printing to console) is the same 3 "words" 2187 times.

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]);
    }
}

}


推荐答案

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

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());
    }
}

这篇关于卡在java电话号码字生成器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆