2013-08-16 34 views
0

我對Java仍然很陌生,一直試圖讓摩斯密碼轉換器工作。我克服了各種錯誤的第一個問題,但現在程序編譯但不會打印翻譯結果。任何幫助,將不勝感激。System.out.println不打印陣列數據

import java.util.Scanner; 

public class MorseCode 
{ 
    public static void main(String[] args) 
    { 
     Scanner Input = new Scanner(System.in); 

     System.out.println("To convert English to Morse Code, type M. To convert Morse Code to English, type E."); 

     String cType = Input.nextLine(); 

     String type = cType.toLowerCase(); 

     if(type == "m") 
     { 
      String eng; 
      System.out.println("Please enter the English text to be translated."); 
      eng = Input.nextLine(); 
      EToM(eng); 
     } 
     else 
     { 
      String morse; 
      System.out.println("Please enter the Morse code text to be translated, with multiple words seperated by a |."); 
      morse = Input.nextLine(); 
      MToE(morse); 
     } 
    } 
    public static void EToM(String eng) 
    { 
     String EToMList[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".--", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "----.", "-----", "|"}; 

     String alphabet = "abcdefghijklmnopqrstuvwxyz123456789 "; 
     String translation[] = new String[eng.length()]; 

     for(int x = 0; x < eng.length(); x++) 
     { 
      for(int y = 0; y < alphabet.length(); y++) 
      { 
       if(eng.charAt(x) == alphabet.charAt(y)) 
       { 
        translation[x] = EToMList[y]; 
        System.out.println("test"); 
       } 
      } 
     } 

     System.out.println("Your translated message is:"); 

     for(int z = 0; z < eng.length(); z++) 
     { 
      System.out.println(translation[z]); 
     } 
    } 

    public static void MToE(String morse) 
    { 

    } 
}  
+0

嘗試打印出來的東西你打印出數組的內容後,看對於字符串/對象比較,循環中有多少次迭代正在運行 –

+1

並使用equals()代替== – kosa

+0

雖然您的方法在編碼方面效率非常低,但編譯並運行良好([演示鏈接](http://ideone.com/UGDpGB))。 – dasblinkenlight

回答

3

你的問題是

if(type == "m") 

使用

if("m".equals(type)) 

if-else會去else,因爲你是比較字符串引用而不是字符串值。 else調用了空的MToE方法。閱讀本文:How Do I compare Strings in Java

+0

它看起來像我希望OP在打印翻譯之前發生的所有事情。如果'type ==「m」'是問題,那麼它甚至不會打印出OP有 –

+0

@SamIam的''test''行,我還沒有看到OP狀態'test'已經打印。 –

+0

爲什麼OP會告訴你,如果在「結果」之前有失敗的證據,問題出現在「結果」中? –

0

在Java中檢查字符串是否相等時,請始終在String類上使用equals方法。更改如下:

if(type == "m") 

if(type.equals("m")) 

使英語莫爾斯電碼翻譯輸出。

我做了這個修改,並且剛剛成功運行它。

0

使用此

if(type.equalsIgnoreCase("m") 
    { 

    }