2013-08-16 35 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") 
    { 

    }