[英]System.out.println not printing array data
我仍然是Java的新手,并一直试图让莫尔斯电码转换器工作。 我克服了各种错误的第一个问题,但现在程序编译但不会打印翻译结果。 任何帮助,将不胜感激。
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)
{
}
}
你的问题是
if(type == "m")
采用
if("m".equals(type))
你的if-else
将转到else
因为你正在比较String引用而不是String值。 else
调用空的MToE
方法。 阅读: 如何比较Java中的字符串
在Java中检查字符串是否相等时,请始终在String类上使用equals方法。 更改以下内容:
if(type == "m")
至
if(type.equals("m"))
使英语到莫尔斯代码翻译输出。
我做了这个修改,刚才成功运行了。
用这个
if(type.equalsIgnoreCase("m")
{
}
您可以使用Java中的deepToString方法打印出您的数组。
文档链接: http : //docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#deepToString(java.lang.Object [])
这是一个代码示例:
System.out.println("Your translated message is:" + java.util.Arrays.deepToString(translation));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.