Java翻译错误。我试图获取用户输入并将其转换为数组中的值

时间:2016-02-20 20:11:36

标签: java arrays loops

我正在制作一个翻译器,它将英语翻译成一种名为 Talhamr 的语言。为此,我将用户输入并将其转换为数组。然后我对一个包含英语单词的单词库数组进行测试,其中包含相应的Talhamr单词。如果英语单词有效,我想用相应的Talhamr单词替换它。任何人都可以帮我编码吗?下面是我的代码。

主要课程:

import java.util.Scanner;

public class Translator {
    public static String userInput = "";

    public static String[] wordBank = {"a/an","Ai","about","circa" /*...*/};

    public static void main(String[] args) {
        /**
         * getting input
         */
        Scanner scanner = new Scanner(System.in);
        System.out.print("Write something to be translated into ancient language: ");
        /**
         * formatting input
         */
        userInput.toLowerCase();
        userInput = scanner.nextLine();
        String[] wordArray = userInput.split(" ");
        /**
         * Creating a, and preforming english to talhammir, translation
         */
        EtoT e2t = new EtoT();
        e2t.translateToTalhamr(wordArray, wordBank);
        System.out.println(wordArray[0]);
        /**
         * This is how I formatted the word bank. After I went to quizlet and changed all the spaces between rows and columns to "-"
         * String makeNice = ...;
         * System.out.println("\""+ makeNice.replace("-", "\",\""));
         */

    }//end of main method   
}//end of Translator class

第二类包含翻译方法:

public class EtoT {
    /**
     * establishing word bank to loop through and translate
     */
    public String[] wordBank = {"a/an","Ai","about","circa" /*...*/};

    public EtoT() {
    }

    public String translateToTalhamr(String[] wordArray, String[] wordBank) {
        for (int i=0; i < wordArray.length; i++) {
            System.out.print("'");
            for (int j = 0; j < wordBank.length; j++) {
                System.out.print(".");
                if (wordBank[j] == wordArray[i]) {
                    System.out.print(",");
                    wordArray[i] = wordBank[j + 1];
                } else {
                    wordArray[i] = wordArray[i] + "!";
                }
            }//end of inner word bank
        }//end of outer for loop
        System.out.println("\n" + wordArray.toString());
        return wordArray.toString();
    }//end of translateToTalhamr

    public static void main(String[] args) {
    }//end of main method
}//end of EtoT

1 个答案:

答案 0 :(得分:0)

您的问题是您使用==比较字符串。因为字符串是对象,所以它会检查它们是否是同一个对象而不是它们具有相同的文本。要正确测试,可以使用string1.equals(string2)

专门针对您,在translateToTalhamr函数中,您应该wordBank[j].equals(wordArray[i])而不是wordBank[j] == wordArray[i]