2013-06-01 24 views
0

我已經創建了這個應用程序,用於類似的編碼和解碼。我創建了用戶輸入文本的第一個文本區域。程序獲取文本。到現在爲止還挺好。
現在我需要用另一組字母或數字或兩者替換每個字母。我試着使用:需要幫助創建一個java(fx)程序,用另一組字符串替換字符串

@FXML 
String text; 
@FXML 
TextArea userText; 
@FXML 
Label codedTextLabel; 
@FXML  
private void getTextAction(ActionEvent textEvent) { 
String codedText; 
    text = userText.getText(); 
    //The first if 
    if (text.contains("a") { 
    codedText = codedTextLabel.getText() + "50"; //50 means a, 60 means b and so on 
    codedTextLabel.setText(codedText); 
    } else { 
    System.out.println("Searching for more text..."); 
    } 
    //The second if 
    if (text.contains("b") { 
    codedText = codedTextLabel.getText() + "50"; //50 means a, 60 means b and so on 
    codedTextLabel.setText(codedText); 
    } else { 
    System.out.println("Searching for more text..."); 

...等等...
我創建了多個IFS爲同一文本區域,讓每個如果得到執行,即使其他執行。但它會產生錯誤並且不起作用。任何想法如何創建這樣的應用程序來做到這一點?

+0

什麼文字,你有你的標籤嗎?你期望輸出什麼?你會得到什麼? – assylias

+0

@assylias錯誤是,如果我寫了重複字母,如ababab,結果只有5060。我需要它是506050605060. –

回答

1

我會做這樣的:

private static final Map<Character, String> mapping = new HashMap <>(); 
static { 
    map.put('a', "50"); 
    map.put('b', "60"); 
    //etc. 
} 

那麼在你的方法:

String text = userText.getText(); 
StringBuilder sb = new StringBuilder(); 
for (char c : text.toCharArray()) { 
    sb.append(mapping.get(c)); //should add null check here 
} 

String encodedText = sb.toString(); 
+0

請解釋你的代碼(兩部分)。什麼是映射?它可以用與fx控制器中的上述相同的方式使用嗎?什麼是stringbuilder? .toCharArray()做什麼? –

+0

'private static final' ...給非法表達式開始 –

+0

@PratikAnand您需要將第一個代碼塊放在您的方法之外。該映射是[兩個字符集之間的對應關係表](http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html),用於高效查找。 [StringBuilder就是這麼說](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html):它比字符串連接更有效地構建字符串。 ['String.toCharArray'返回字符串中的單個字符](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray%28%29),所以我們可以迭代它們。 – assylias

相關問題