textview

时间:2016-03-27 08:29:04

标签: java android if-statement

我正在使用我的翻译应用程序,我的主翻译中遇到了一些问题。 例如,像我下面的代码,我试图改变" bed"进入"坏"如果最后一个字符是" m"它将转变为" t"。

当我的输入是" BEDROOM"我想把它变成" BADROOT"下面的代码只是读了我的第一个声明,另一个变成了假。

     private void MachinetranslatorO(){
     String change= input.getText().toString();
    if (change.substring(0,3).equals("bed")){
        String change1 = change.replaceFirst("bed", "bad");
        result.setText(change1);
    if (change.substring(change.length()-1).equals("m")){
            char replaceWith='t';
            StringBuffer aBuffer = new StringBuffer(change);
             aBuffer.setCharAt(change.length()-1, replaceWith);
             result.setText(aBuffer)

2 个答案:

答案 0 :(得分:0)

您的第一个声明正常但在此之后您将新的reult分配给change1而不是更改。因此,在您的第二个if语句中,您应该使用较新的字符串 - change1。不要在第二个if语句中使用旧的字符串更改。

在第二个if语句中用change1替换更改。

**编辑 - **

private void MachinetranslatorO(){
 String change= input.getText().toString();
 String change1;
if (change.substring(0,3).equals("bed")){
    change1 = change.replaceFirst("bed", "bad");
    result.setText(change1);

if (change1.substring(change1.length()-1).equals("m")){
        char replaceWith='t';
        StringBuffer aBuffer = new StringBuffer(change1);
         aBuffer.setCharAt(change1.length()-1, replaceWith);
         result.setText(aBuffer)

答案 1 :(得分:0)

嗯...因为你问我会提供一个快速的小型Java控制台可运行。代码评论很好,所以你应该没有麻烦跟着它。

此应用程序需要一个包含翻译数据的文本文件(在本例中为英语到西班牙语),我还提供了本文末尾的样本数据。

运行应用程序并输入翻译表数据文件(spanish.txt)中包含的任何一个英语单词,程序将显示西班牙语等效文件。

使用您喜欢的IDE创建一个名为 LanguageTranslator 的新项目,然后复制/粘贴以下代码:

package languagetranslator;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class LanguageTranslator {
    // Declare and intitialize some Class global variables...
    // The language. It is also the name of our translation table 
    // text file (ie: spanish.txt)
    private static String language = "spanish";
    // The 2 Dimensional Array which will hold our translation table.
    private static String[][] translationTable = {};


    // Class main() method
    public static void main(String[] args) {
        // Load up the translationTable[][] 2D String Array from our
        // Tanslation Table text file (spanish.txt).
        readInTranslationFile(language + ".txt");

        // Declare and initialize our String variable we will use to accept
        // console input from User with...
        String userInput = "lets go";

        // Open a Connection to console Using the Scanner Class
        try (Scanner conInput = new Scanner(System.in)) {
            // Start a while/loop to continually ask the User to 
            // supply a English word...
            while (!userInput.equals("")) {
                // Ask User to supply a Word...
                System.out.println("\nPlease supply a English word to translate\n"
                        + "or supply nothing to exit:");
                // Hold what User enters into console within the userInput variable.
                userInput = conInput.nextLine();
                // If the User supplied nothing then he/she want to quit.
                if (userInput.equals("")) { break; }

                // Declare and initialize a boolean variable so as to later determine if
                // a translation for the supplied word had been found.
                boolean found = false;
                // Iterate through the translationTable[][] 2D String Array to see if
                // the User's supplied word is contained within. The English word to 
                // match would be in the first column of the array and the translation
                // for that word would be in the second column of the array.
                for (int i = 0; i < translationTable.length; i++) {
                    // convert the word supplied by User and the current word being read
                    // within column 1 of the 2D Array to lowercase so that letter case
                    // is not a factor here.
                    if(userInput.toLowerCase().equals(translationTable[i][0].toLowerCase())) {
                        // If the word supplied by User is found within the translationTable[][]
                        // array then set the found variable to true and display the spanish
                        // translation to console.
                        found = true;
                        System.out.println("--------------------------------------");
                        System.out.println("The " + language + " translation is: \u001B[34m" 
                                + translationTable[i][1] + "\u001B[39;49m");
                        System.out.println("--------------------------------------");
                    }
                }
                // If we've iterated through the entire tanslationTable array and an a match
                // was not found then display as such to the User...
                if (!found) {
                    System.out.println("\n\u001B[31mThe supplied word could not be located within "
                            + "the Translation Table.\n\u001B[39;49m");
                }
                // Continue the while/loop and ask User to supply another word
                // until the User supplies nothing.
            }
        }
        // Exit the application if nothing is supplied by User.
        System.exit(0);
    }


    // Method used to fill the tanslationTable[][] 2D String Array from 
    // a text file which contains all the translation data.
    private static void readInTranslationFile(String filePath) {
        String line = "";
        int cnt = 0;
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            // Read in each line of the tanslation Table text file so as to place each
            //line of data into the translationTable[][] 2 String Array...
            while((line = br.readLine()) != null){
                // Skip past blank lines in the text file and only process file lines
                // which actually contain data.
                if (!line.equals("")) { 
                    // Each line of data within the Translation table text file consists
                    // of a |English word and it's Spanish equivalent delimited with a 
                    // Pipe (|) character. A pipe character is used because you may later
                    // want to add definitions to your data that may contain different types 
                    // of punctuation.
                    String[] tok = line.split("\\|");
                    // The redimPreserve() method allows for appending to a raw 2D String 
                    // Array on the fly.
                    translationTable = redimPreserve(translationTable, cnt + 1, 2);
                    // Add the file data line to the 2D String Array...
                    translationTable[cnt][0] = tok[0].trim();
                    translationTable[cnt][1] = tok[1].trim();
                    cnt++; // counter used for incrementing the 2D Array as items are added.
                }
            }
            // Close the BufferReader
            br.close();
        } 
        // Trap IO Exceptions from the Bufferreader if any...
        catch (IOException ex) {
            System.out.println("\n\u001B[31mThe supplied Translation Table file could"
                             + " not be found!\n\u001B[39;49m" + filePath);
        }
    }


    // The redimPreserve() method allows for appending to a raw 2D String 
    // Array on the fly. I created this method to make the task esier to
    // accomplish.
    private static String[][] redimPreserve(String[][] yourArray, int newRowSize, int... newColSize) {
        int newCol = 0;
        if (newColSize.length != 0) { newCol = newColSize[0]; }
        // The first row of your supplied 2D array will always establish
        // the number of columns that will be contained within the entire
        // scope of the array. Any column value passed to this method
        // after the first row has been established is simply ignored.
        if (newRowSize > 1 && yourArray.length != 0) { newCol = yourArray[0].length; }
        if (newCol == 0 && newRowSize <= 1) {
            JOptionPane.showMessageDialog (null,"RedimPreserve() Error\n\n"
                             + "No Column dimension provided for 2D Array!",
                               "RedimPreserve() Error",JOptionPane.ERROR_MESSAGE);
            return null;
        }
        if (newCol > 0 && newRowSize < 1 && yourArray.length != 0) {
            JOptionPane.showMessageDialog (null,"RedimPreserve() Error\n\n"
                                + "No Row dimension provided for 2D Array!",
                                  "RedimPreserve() Error",JOptionPane.ERROR_MESSAGE);
            return null;
        }
        String[][] tmp = new String[newRowSize][newCol];
        if (yourArray.length != 0) {
            tmp = Array2DCopy(yourArray, tmp);
        }
        return tmp; 
    }

    // Used within the redimPreserve() method to copy 2D Arrays.
    private static String[][] Array2DCopy(String[][] yourArray, String[][] targetArray) {
        for(int i = 0; i < yourArray.length; i++) {
            System.arraycopy(yourArray[i], 0, targetArray[i], 0, yourArray[i].length);
        }
        return targetArray;
    }
}

对于示例翻译表文本文件,您可以将以下行复制/粘贴到文本编辑器中,并将文件另存为&#34; spanish.txt&#34;在项目的 Classpath (LanguageTranslator)中:

0|el cero
1|un
2|dos
3|tres
4|cuatro
5|cinco
6|seis
7|siete
8|ocho
9|nueve

a|un
able|poder
also|además
always|siempre
anyway|de todas formas
anyways|de todos modos
an|un
and|y
any|alguna
anybody|nadie
anything|cualquier cosa
apple|manzana

banana|platano
be|ser
because|porque
bedroom|cuarto
best|mejor

can|poder
can't|hipocresia

date|fecha

easy|facil

hard|difícil
harder|mas fuerte

now|ahora
never|nunca
new|nuevo

goodbye|adiós

hello|hola
her|su
high|alto
him|el
his|su
home|casa
how|como

in|en
inside|dentro
is|es
isn't|no es
it|eso
it's|sus
its|sus

leave|salir
list|lista
low|bajo
love|amor

of|de
out|fuera
outside|fuera de
over|encima

that|ese
the|la
then|entonces
these|estas
this|esta
those|aquellos
top|parte superior
topped|rematada
time|hora
to|a

was|estaba
weather|clima
what|que
where|donde
whether|si
who|quien
why|por que

you|tu
your|tu

如果您愿意,可以根据需要添加数据。 希望这会有所帮助...