2016-03-27 4 views
-1

私の翻訳アプリケーションでやっている、私は主な翻訳者にいくつか問題があります。 例えば以下のコードのように "bed"を "bad"に変換しようとします。最後のcharが "m"なら "t"に変換します。テキストビューの文字列と文字の置換

入力が「BEDROOM」のとき、私は最初のステートメントを読むだけのコードを「BADROOT」に変換し、もう1つは偽になりました。

 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) 
+0

翻訳する英語の単語はいくつですか?私はif/thenのステートメントがここで起こっているのを見ることができます。 2次元配列を変換テーブルとして使用し、入力文字列と配列の両方を繰り返してString.replace()を使用して変換を行うことを検討することもできます。 – DevilsHnd

+0

あなたのインデントは、最初の条件付きブロックとおそらく2番目の条件ブロックのブレースを閉じるのを忘れたことを示唆しています。 – user2570380

+0

@DevilsHnd参考文献はありますか? – LiamJuniors

答えて

0

うーん...あなたは、私が実行可能な小さなクイックJavaコンソールを提供しますので、尋ねました。コードはかなりコメントされているので、それに続く問題はないはずです。

このアプリケーションでは、翻訳データ(この例では英語からスペイン語)を含むテキストファイルが必要です。このテキストファイルには、この記事の末尾にサンプルデータもあります。

アプリケーションを実行し、翻訳テーブルデータファイル(spanish.txt)に含まれる英語の単語のいずれか1つを入力すると、プログラムはスペイン語の同等のものを表示します。あなたがテキストに以下の行をコピー/ペーストすることができますサンプルの変換テーブルのテキストファイルの

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

は、単にその後、以下のコードをコピー/ペーストし、あなたの好きなIDEを使用して、新しい名前のプロジェクトLanguageTranslatorを作成しますエディタや、プロジェクトのクラスパス以内に「spanish.txt」としてファイルを保存します(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 

は、データを追加あなたが好きならファイル。 これが役に立ちますようお願い致します...

+0

ありがとう、このコードは私を保存:) – LiamJuniors

0

あなたの最初のステートメントはうまくいきますが、それ以降は新しい変更をchange1に割り当てます。したがって、2番目のif文では、新しい形式の文字列 - change1を使用する必要があります。 2番目のif文で古い文字列の変更を使用しないでください。

2番目のif文でchange1をchange1に置き換えます。

** EDIT - **

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) 
+0

change1は解決できません – LiamJuniors

+0

私の編集@LiamJuniorsを参照してください –