摩尔斯电码转换器,它将字符串作为用户的输入并将其转换为莫尔斯电码。使用的变量和方法是问题所需的唯一方法
我想知道,如何有效地使用getMorseCode()
和getOriginals()
方法。
另外,如果我编码的程序是好的,请告诉我。
我认为有些问题是错误的,因为当我从Morse
类调用getter时,它们只显示为空。
Morse
上课:
public class Morse {
public int NUM_CHARS = 40;
private String original;
private String mcode;
private char[] regular = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };;
private String[] morse = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----"};;
public Morse(String input) {
String original = input;
for (int i=0; i<original.length(); i++){
char cha = original.charAt(i);
String mcode = toMorse(cha);
System.out.print(mcode +"");
//mcode = getMorseCode();
}
}
public String toMorse(char ch) {
String morseCode = "";
for (int i = 0; i < 36; i++) {
if (ch == regular[i])
morseCode = morse[i];
}
return morseCode;
}
public String getMorseCode() {
return mcode ;
}
public String getOriginal() {
return original;
}
}
MorseCodeConverter
上课:
import java.util.Scanner;
public class MorseCodeConverter {
public static void main (String [] args){
char answer = 'Y';
Scanner kb = new Scanner (System.in);
String response;
do{
System.out.println("Enter the english text to be converted: ");
String sentence = kb.nextLine();
System.out.println("The code is: ");
Morse code = new Morse (sentence);
System.out.println();
//System.out.println(code.getMorseCode());
System.out.println("Do you want to continue (Y/N)?");
response = kb.nextLine(); // User's response
answer = response.charAt(0); // Getting the character at 0th position
} while (Character.toUpperCase (answer) == 'Y');
}
}
答案 0 :(得分:2)
这里:
for (int i=0; i<original.length(); i++){
char cha = original.charAt(i);
String mcode = toMorse(cha);
System.out.print(mcode +"");
//mcode = getMorseCode();
}
你没有积累摩尔斯电码,你取代以前翻译过的新电影。声明一个StringBuilder,然后在循环之前移动它
例如:
StringBuilder builder = new StringBuilder();
for (int i=0; i<original.length(); i++){
char cha = original.charAt(i);
builder.append(toMorse(cha));
}
this.mcode = builder.toString();
此外,作为改进而不是在toMorse()
中迭代以找到匹配的字符,请使用Map
作为关键字存储常规字符,并将morse字符作为值存储。
Map<Character, String> morseCodesByRegularChar = new HashMap<>();
morseCodesByRegularChar.put('a', ".-");
morseCodesByRegularChar.put('b', "-...");
// and so for
您可以通过以下方式替换toMorse()
调用:
char cha = ...
String morseCode = morseCodesByRegularChar.getOrDefault(cha, "");
答案 1 :(得分:1)
你没有为getOriginal()和getMorseCode()获取任何内容的原因是因为在你的constuctor中你在其本地范围内创建了名为original和mcode的新变量。请改用全局变量。 所以,试试:
String mcode = "";
String original = "";
public Morse(String input){
original = input; //instead of String original
for (char letter : input.toCharArray()){
mcode += toMorse(letter); //instead of String mcode
}
}