尝试从字符串数组创建一个字符串

时间:2016-03-01 01:46:54

标签: java arrays string java-8

我会在这个问题上加上这样一个事实,即我只用了一个月的时间来学习编程,这对于学校的任务让我很难过。具体来说,它是莫尔斯电码到英语翻译(反之亦然)......这是我坚持的部分:

/* 
*  A program that asks the user to select which they would like to do: translate 
*  from English to Morse code, or Morse code to English. The list of characters 
*  for each language is stored using arrays. The program will then perform and return
*  the translations.
*/
import java.util.Scanner;

public class MorseEnglishTranslator
{

    public static void main( String [] args )
    {
        int translateChoice = 0;                   // Variable for person's choice for direction of translation

        Scanner inputText = new Scanner( System.in );  // Create a Scanner to obtain user input
        System.out.print( "Enter 1 to translate from English to Morse code, 2 for Morse code to English: " );
        translateChoice = inputText.nextInt();

        if (translateChoice == 1);
            {        
                System.out.print("Enter a letter, word, or phrase you would like translated: ");
            }    
        if (translateChoice == 2);
            {
                System.out.print("Enter the Morse code you would like translated, separate letters and words with a |: ");
            }
        String userStr = inputText.nextLine();

        translator( translateChoice, userStr);


    } // Closes main

    public static void translator( int translateChoice, String userStr) // Method for translating either direction
    {
        String english [] = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
                             "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6",
                             "7", "8", "9", "0", " "};

        String s1 = String.join(" ", english);  // Assigns the contents of english array to one string

        String morse [] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", 
                           "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
                           "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..",
                           "----.", "-----", "|"};

        String s2 = String.join("|", morse);    // Assigns the contents of morse array to one searchable string

        if (translateChoice == 1);
            {        
                String userStrLower = userStr.toLowerCase();  // In case user capitalized anything, changes everything to lowercase
                for (int allFound=0; allFound <userStrLower.length(); allFound ++)
                {
                    allFound = s1.indexOf( userStrLower );  // Variable 'allFound' to receive the search of s1 using userStrLower
                    System.out.print( allFound );
                } 
            }    
        if (translateChoice == 2);
            {
                for (int allFound=0; allFound <userStr.length(); allFound ++)
                {
                    allFound = s2.indexOf( userStr );  // Variable 'allFound' to receive the search of s2 using userStr
                    System.out.print( allFound );
                }   
            }

    } // Closes translator        
} // Closes class

字符串s1和s2是我正在考虑使用的两个选项,但是s1版本在New之后告诉我有一个预期的分号。我尝试作为String.join vs join的join选项表示没有合适的构造函数vs分别找不到符号。

1 个答案:

答案 0 :(得分:-1)

我知道你是Java课程的介绍,所以随意提问,但你1)不需要加入字符串2)indexOf对于你需要它的目的来说效率很低对于。 HashMap<String, String>是译者的完美对象。

我制作了这个可以在两个String数组之间来回切换的双向map类。将其保存到BiMap.java文件中。

import java.util.HashMap;

public class BiMap {
    private HashMap<String, String> forwardMap;
    private HashMap<String, String> backwardMap;

    public BiMap(String[] from, String[] to) {
        forwardMap = new HashMap<>();
        backwardMap = new HashMap<>();

        for (int i = 0; i < from.length && i < to.length; i++) {
            forwardMap.put(from[i], to[i]);
            backwardMap.put(to[i], from[i]);
        }
    }

    public String translateForward(String key) {
        return forwardMap.get(key);
    }

    public String translateBackward(String key) {
        return backwardMap.get(key);
    }
}

以下是该类的示例用法。您可以随意添加用户提示。对于类变量常量,建议使用static final修饰符。然后,我定义了一些private方法来提取翻译逻辑。

在学习时尽可能多地编写可读和可重用的方法是一种很好的做法。

public class MorseEnglishTranslator {

    private static final String[] ENGLISH = new String[]{
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
            "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z", "1", "2", "3", "4",
            "5", "6", "7", "8", "9", "0", " "};

    private static final String[] MORSE = new String[]{
            ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
            "....", "..", ".---", "-.-", ".-..", "--", "-.",
            "---", ".--.", "--.-", ".-.", "...", "-", "..-",
            "...-", ".--", "-..-", "-.--", "--..", ".----",
            "..---", "...--", "....-", ".....", "-....",
            "--...", "---..", "----.", "-----", "|"};

    private static final BiMap MORSE_MAP = new BiMap(ENGLISH, MORSE);

    private static final String DELIMITER = " ";

    private static String toMorse(String s) {
        StringBuilder sb = new StringBuilder();
        String lower = s.toLowerCase();
        for (int i = 0; i < lower.length(); i++) {
            String c = String.valueOf(lower.charAt(i));
            sb.append(MORSE_MAP.translateForward(c)).append(DELIMITER);
        }
        return sb.toString();
    }

    private static String fromMorse(String s) {
        String[] split = s.split(DELIMITER);
        StringBuilder sb = new StringBuilder();
        for (String morse : split) {
            sb.append(MORSE_MAP.translateBackward(morse));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String sentence = "Hello World";
        String morse = toMorse(sentence);
        String translated = fromMorse(morse);

        System.out.println(sentence);
        System.out.println(morse);
        System.out.println(translated);
        System.out.println(sentence.equalsIgnoreCase(translated));

    }

}

样品运行

Hello World
.... . .-.. .-.. --- | .-- --- .-. .-.. -.. 
hello world
true
相关问题