该代码假定是从英语翻译为莫尔斯电码。一切正常,除了for循环外,它仅转换Message(String A)
的第一个字母。
为什么?
例如,我使字符串A =“ America” ...然后变成“ america”(由于toLowerCase()),但是当它进入for循环时,它将仅转换第一个“ a”,就这样,像这样:
“ .- ||||||||”(a= ".-")..
我的代码:
import java.util.Scanner;
class MORSE3{
public static void main(String[] args){
String A;
Scanner bola=new Scanner(System.in);
System.out.println("Introdusca la frase: ");
A=bola.nextLine();
int B=A.length();
int C,X,Y;
Y=1;
X=0;
System.out.println("Traduccion: ");
String Mor[]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-..","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
A=A.toLowerCase();//Para hacer las letra minusculas;
System.out.println(A.charAt(X));
for(C=0;C<B;C++){
switch(A.substring(X,Y)){
case "a":
System.out.print(Mor[0]+"|");
X+=1;
Y+=1;
break;
case "b":
System.out.print(Mor[1]+"|");
X+=1;
Y+=1;
break;
case "c":
System.out.print(Mor[2]+"|");
X+=1;
Y+=1;
break;
case "d":
System.out.print(Mor[3]+"|");
X+=1;
Y+=1;
break;
case "e":
System.out.print(Mor[4]+"|");
X+=1;
Y+=1;
break;
case "f":
System.out.print(Mor[5]+"|");
X+=1;
Y+=1;
break;
case "g":
System.out.print(Mor[6]+"|");
X+=1;
Y+=1;
break;
case "h":
System.out.print(Mor[7]+"|");
X+=1;
Y+=1;
break;
case "i":
System.out.print(Mor[8]+"|");
X+=1;
Y+=1;
break;
case "j":
System.out.print(Mor[9]+"|");
X+=1;
Y+=1;
break;
case "k":
System.out.print(Mor[10]+"|");
X+=1;
Y+=1;
break;
case "l":
System.out.print(Mor[11]+"|");
X+=1;
Y+=1;
break;
case "m":
System.out.print(Mor[12]+"|");
X+=1;
Y+=1;
break;
case "n":
System.out.print(Mor[13]+"|");
X+=1;
Y+=1;
break;
case "o":
System.out.print(Mor[14]+"|");
X+=1;
Y+=1;
break;
case "p":
System.out.print(Mor[15]+"|");
X+=1;
Y+=1;
break;
case "q":
System.out.print(Mor[16]+"|");
X+=1;
Y+=1;
break;
case "r":
System.out.print(Mor[17]+"|");
X+=1;
Y+=1;
break;
case "s":
System.out.print(Mor[18]+"|");
X+=1;
Y+=1;
break;
case "t":
System.out.print(Mor[19]+"|");
X+=1;
Y+=1;
break;
case "u":
System.out.print(Mor[20]+"|");
X+=1;
Y+=1;
break;
case "v":
System.out.print(Mor[21]+"|");
X+=1;
Y+=1;
break;
case "w":
System.out.print(Mor[22]+"|");
X+=1;
Y+=1;
break;
case "x":
System.out.print(Mor[23]+"|");
X+=1;
Y+=1;
break;
case "y":
System.out.print(Mor[24]+"|");
X+=1;
break;
case "z":
System.out.print(Mor[25]+"|");
X+=1;
Y+=1;
break;
default:
System.out.print("|");
break;
}
}
}
}
最佳答案
我不知道您要写的是什么,而不是Y=Y;
,但这没有任何效果(我看不到声明Y
的位置)。您不需要带子字符串-只需使用输入字符串的字符即可。
注意:如果使用'a' - 'a' = 0
,'b' - 'a' = 1
等属性(因此A. charAt(C)-'a')将帮助您摆脱此开关,则您的代码可能会更短。
关于java - 英语到莫尔斯电码翻译器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23579155/