Java:莫尔斯电码转换器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1856501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:15:42  来源:igfitidea点击:

Java: MorseCode Converter

javamorse-code

提问by HelloWorld

I'm trying to convert Morse code into text.

我正在尝试将摩尔斯电码转换为文本。

I have two text files to use with this problem. morseCode.txt: I have a file that i read off that contains the letters and corresponding Morse code equivalent.

我有两个文本文件可用于解决此问题。morseCode.txt:我有一个文件,我读了它,其中包含字母和相应的莫尔斯电码。

morse.dat: Its the file that contains the encrypted message in Morse code

morse.dat:包含莫尔斯电码加密信息的文件

I was able to read the first file properly and then store then into separate arrays. I tested it by printing the array for letters and array morse code and found that it did store it properly and in order.

我能够正确读取第一个文件,然后将其存储到单独的数组中。我通过打印字母数组和数组莫尔斯电码来测试它,发现它确实按顺序正确存储了它。

I'm having problems with reading the message the second file. This is the morseCode.txt key:

我在阅读第二个文件的消息时遇到问题。这是 morseCode.txt 键:

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   --..
0   ----- 
1   .---- 
2   ..--- 
3   ...-- 
4   ....- 
5   ..... 
6   -.... 
7   --... 
8   ---.. 
9   ----. 
.  .-.-.- 
,   --..-- 
?   ..--.. 

This is what the Message.txt file looks like:

这是 Message.txt 文件的样子:

    - .... .. ... 
.. ... 
.- 
- . ... - 
.--. .-. --- --. .-. .- -- .-.-.- 
.. ..-. 
-.-- --- ..- 
... . . 
- .... .. ... 
-- . ... ... .- --. . 
- .... .- - 
.. ... 
--. --- --- -.. 
-. . .-- ... 
-.-- --- ..- .-. 
.--. .-. --- --. .-. .- -- 
.-- --- .-. -.- ... .-.-.- 

Its supposed to ouput:

它应该输出:

THIS IS A TEST PROGRAM.
IF YOU SEE THIS MESSAGE THAT IS GOOD NEWS YOUR PROGRAM WORKS.

+++THIS IS MY SOLUTION.+++

+++这是我的解决方案。+++

/*     
 *This is a program that translates Morse Code to English text. The key is read from a file. 
 *
 *The file contains the equivalent letters and Morse code. The entire key is stored in an array for reference. 
 *
 *A second file contains the encrypted message. The program reads the message file and converts individual Morse code 
 *
 *letters into alphabet letters. The results are displayed and printed out to another file. */

import java.io.*;
import java.util.Scanner;

//file writer and print writer to save the output
public class Assignment4
{
 @SuppressWarnings("null")
 public static void main (String [] args) throws IOException
 {
  //arrays for letters and Morse Code values
  String[] letter = new String[39], morseCode = new String[39];     
  //this is the file with the letters and morse code equivalent
  File file1 = new File ("c:/morseCode.txt");
  Scanner in = new Scanner(file1);  

  int i = 0;

  while (in.hasNext())
        {
            //read in letter
   letter[i] = in.next();   
   //read in Morse Code
            morseCode[i] = in.next();          

            i++;
        }

  //this is the file with encrypted message
  String morseLine, morseLetter, theLetter = " ";  
  //this file contains the encrypted message
  File file2 = new File ("c:/morse.dat");
  Scanner data = new Scanner(file2);

  //this appends the data to the file and keeps a running input 
  FileWriter fWriter = new FileWriter("c:/Message.txt", true);
  PrintWriter outPutFile = new PrintWriter(fWriter);

  boolean found; 
  int  number = morseCode.length; 

  while (data.hasNext())
  {
   //reads each line of mesage
   morseLine = data.nextLine(); 

   i = 0; 
   int j = 0,  k = 0;      
   j = morseLine.indexOf(" ");   

   while (j != -1)
   {
    //determines the end of a letter in Morse code and stores the 
    morseLetter = morseLine.substring(i, j);

    found = false;    
    k = 0;    
    theLetter = " ";

    //this loop searches the array of morseCode for the equal Morse code letter
    //then it assigns the corresponding letter that is equivalent
    while (k < number && !found)
    {
     if (morseLetter.equals(morseCode[k]))
     {
      theLetter = letter[k];      
      found = true;
     }

     else
     {
      k++;
     }
    }

    //this condition prints the equivalent letter of the Morse code letter
    //on the message
    if (!theLetter.equals(" "))
    {
     System.out.print(theLetter);     
     outPutFile.print(theLetter);
    }

    i = j + 1;    
    j =  morseLine.indexOf(" ", i);    
   }   

   if(theLetter.equals("."))
   {
    //moves to the next line at the end of the sentence
    System.out.println(""); 
    outPutFile.println("");
   }

   else
   {
    //this separates the letters into words
    System.out.print(" "); 
    outPutFile.print(" ");
   }
  }

  outPutFile.close();
    }
}

采纳答案by Mark Byers

You will have a problem using Scanner to parse the morse.dat file because there are two types of delimiter - a space and a new line. The easiest way is probably to read one line at a time using a BufferedReader, and split the line on a space. Here is the code to do that. I avoided using methods because you haven't learned about them yet.

使用 Scanner 解析 morse.dat 文件时会遇到问题,因为有两种类型的分隔符 - 空格和换行符。最简单的方法可能是使用 BufferedReader 一次读取一行,并将该行拆分为一个空格。这是执行此操作的代码。我避免使用方法,因为你还没有了解它们。

import java.io.*;
import java.util.*;

public class Assignment4
{
    public static void main(String[] args) throws IOException
    {
        Map<String, String> morseCodes = new HashMap<String, String>();
        File file1 = new File ("morsecode.txt");
        Scanner in = new Scanner(file1);  

        while (in.hasNext())
        {
            String letter = in.next();          
            String code = in.next();   
            morseCodes.put(code, letter);
        }

        File morseCode = new File("message.txt");
        BufferedReader bufferedReader = new BufferedReader(new FileReader(morseCode));
        String line;

        while ((line = bufferedReader.readLine()) != null)
        {
            String letter = "";

            for (String morseLetter: line.split(" "))
            {
                letter = morseCodes.get(morseLetter);
                System.out.print(letter);
            }

            if (letter.equals(".")) {
                // Insert a new line after a period.
                System.out.println();
            } else {
                // Insert a space between words.
                System.out.print(' ');
            }
        }
    }
}

Output of above program:

上述程序的输出:

THIS IS A TEST PROGRAM.
IF YOU SEE THIS MESSAGE THAT IS GOOD NEWS YOUR PROGRAM WORKS.

I hope that helps you!

我希望对你有帮助!

回答by Anon.

while (data.hasNext())
{
   //read in letter
           words[e] = message[e].indexOf(" ");
while (data.hasNext())
{
   //read in letter
           words[e] = message[e].indexOf(" ");

Considering you open the file as dataand don't actually do anything with it, I'm not surprised it isn't working.

考虑到您打开文件data并且实际上并没有对其进行任何操作,我并不感到惊讶它不起作用。

You want to get the individual tokens from the data file, and then look up their index in your morse array.

您想从数据文件中获取各个标记,然后在您的莫尔斯数组中查找它们的索引。