Morse1010 Translating Text to Morse Code *

Similar documents
Authoring OpenStax Documents in Apache OpenOffice Writer *

Java3018: Darkening, Brightening, and Tinting the Colors in a Picture *

Java4340r: Review. R.G. (Dick) Baldwin. 1 Table of Contents. 2 Preface

OpenStax-CNX module: m Java3002r Review * R.G. (Dick) Baldwin

Java0078 Java OOP Callbacks - II *

Hs01006: Language Features, Arithmetic Operators *

Java OOP: Java Documentation

Java4350: Form Processing with JSP

Java4570: Session Tracking using Cookies *

Using Flex 3 in a Flex 4 World *

Accessible Objected-Oriented Programming Concepts for Blind Students using Java. By: R.G. (Dick) Baldwin

Java4320: Web Programming Model *

INEW Advanced Java Programming. Collection Editor: R.G. (Dick) Baldwin

Java3002: Creating and Manipulating Turtles and Pictures in a World Object *

Java3002: Creating and Manipulating Turtles and Pictures in a World Object

Java1486-Fun with Java, Understanding the Fast Fourier Transform (FFT) Algorithm *

The json-simple Java Library. By: R.G. (Dick) Baldwin

AP Computer Science A, Clarification of the Java Subset. By: R.G. (Dick) Baldwin

Polymorphism - The Big Picture *

MemoryKeyerV2.0.ino (AtoM.h, MtoA.h, Canned.h)

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Impro-Visor. Jazz Improvisation Advisor. Tutorial. Last Revised: 5 June 2006 Currently 62 Steps. Bob Keller. Harvey Mudd College

Basic Programming Language Syntax

Memory Addressing, Binary, and Hexadecimal Review

R-09HR ReleaseNote. R-09HR Operating System Version 2.00 RO9HRRN200

How to make a "hello world" program in Java with Eclipse *

Principles of Compiler Design Prof. Y. N. Srikant Department of Computer Science and Automation Indian Institute of Science, Bangalore

Full file at

GAME Motion Displacement and Vectors

ALICE: An introduction to progamming

Assignment 2, due September 17

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Recording for the Blind Part One

The Default Application Container - Flex 3 and Flex 4 *

the NXT-G programming environment

AP Computer Science Unit 1. Writing Programs Using BlueJ

Copy Music from CDs for Videos & Slideshows

Close Your File Template

Getting Started with Processing by Casey Reas and Ben Fry

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

[ mini-project ] Create standard MIDI files with LabVIEW *

Exercise 4: Loops, Arrays and Files

Usability Report. Author: Stephen Varnado Version: 1.0 Date: November 24, 2014

1 of 24 5/6/2011 2:14 PM

Upload Your Site. & Update. How to

Memory Keyer for the RockMite

Box Plots. OpenStax College

AP Computer Science Unit 1. Writing Programs Using BlueJ

Java Bytecode (binary file)

Introduction. Note: All references to the MFJ-442 apply to the MFJ-442X, unless otherwise stated. Control Functions

Multimedia Programming with Java Getting Started

Introduction to Java Unit 1. Using BlueJ to Write Programs

My Favorite bash Tips and Tricks

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Math Modeling in Java: An S-I Compartment Model

Avaya 9640 IP Telephone End User Guide

CE221 Programming in C++ Part 1 Introduction

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Processing Image Pixels, Creating Visible Watermarks in Java. Preface

Compare quadrilaterals for similarities and differences *

CPS122 Lecture: Defining a Class

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

CSCI 136: Fundamentals of Computer Science II. Keith Vertanen Museum

COMP 110 Project 1 Programming Project Warm-Up Exercise

Hello! My name is PC and I am learning how to use a computer. Let s learn together! Unit1

AP Computer Science Unit 1. Programs

Preprocessor Directives

List Building Starter Course. Lesson 2. Writing Your Campaign. Sean Mize

Lesson 2 page 1. ipad # 17 Font Size for Notepad (and other apps) Task: Program your default text to be smaller or larger for Notepad

Alspaugh Morse Keyboard Encoder Operating Instructions

Lesson Plans. Put It Together! Combining Pictures with Words to Create Your Movie

MP Music & Video Player VOL. User Guide

Sony Ericsson W850i Quick Start Guide

Introduction to the Internet. Part 1. What is the Internet?

Scott D. Lipscomb. Music Education & Music Technology. Tenure Dossier. Electronic Dossier Instructions

GAP CLOSING. Integers. Intermediate / Senior Facilitator s Guide

PYTHON PROGRAMMING FOR BEGINNERS: AN INTRODUCTION TO THE PYTHON COMPUTER LANGUAGE AND COMPUTER PROGRAMMING BY JASON CANNON

Assignment 3: Optimizing solutions

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Memory Keyer for the RockMite

The first program: Little Crab

Functional Programming in Haskell Prof. Madhavan Mukund and S. P. Suresh Chennai Mathematical Institute

WebQuest. Question-File Quick-Start Instructions

How to Change the Default Playback & Recording Audio Device. How to Change the Default Playback Device

CS 177 Week 15 Recitation Slides. Review

Voice Messaging User Guide from Level 3. Updated April Level 3 Communications, LLC. All rights reserved. 1

Burning CDs in Windows XP

(1) (1) English Edition. Tutorial Guide Sony Corporation 2002 Sony Corporation

GAP CLOSING. Grade 9. Facilitator s Guide

Introduction to Linux

The following steps will create an Eclipse project containing source code for Problem Set 1:

How to edit custom layouts in Blurb *

Introduction to Software Development (ISD) David Weston and Igor Razgon

The Essence of OOP using Java, Nested Top-Level Classes. Preface

CS 231 Data Structures and Algorithms, Fall 2016

Unit 1, Lesson 1: Moving in the Plane

CSE Theory of Computing Spring 2018 Project 2-Finite Automata

Working with Apple Loops

Transcription:

OpenStax-CNX module: m60489 1 Morse1010 Translating Text to Morse Code * R.G. (Dick) Baldwin This work is produced by OpenStax-CNX and licensed under the Creative Commons Attribution License 4.0 Abstract Learn how to translate text to Morse code using Java Platform Standard Edition and no special sound libraries. Revised: Fri Apr 29 19:29:20 CDT 2016 This page is part of a Book titled Morse Code and Computer Programs 1. 1 Table of contents Table of contents (p. 1) Preface (p. 2) Viewing tip (p. 2) * Figures (p. 2) * Listings (p. 2) General background information (p. 2) Historical perspective (p. 3) Sounds (p. 3) Using previously published code (p. 3) * How does it sound? (p. 4) Discussion and sample code (p. 4) Beginning of the program (p. 4) Create a hashtable (p. 4) Begin processing the input data stream (p. 6) Get the Morse code for the character (p. 6) The output for HELLO WORLD (p. 7) Display the character and the code (p. 8) Convert the Morse code to musical notes (p. 9) * Interpretation of the programming code (p. 9) * One unit of time (p. 10) * Version 1.3: Apr 29, 2016 7:30 pm -0500 http://creativecommons.org/licenses/by/4.0/ 1 http://cnx.org/contents/zwwykvgc

OpenStax-CNX module: m60489 2 * Morse code speed (p. 10) * Changing the code speed (p. 10) Insert silence between characters (p. 10) Writing the output le (p. 11) Reading the input le (p. 11) Run the program (p. 11) Complete program listing (p. 12) Miscellaneous (p. 15) 2 Preface As I mentioned in an earlier module 2, a few weeks ago, I was asked to assist a grandchild who was working on a science project involving Morse code. I went online and searched for a stand-alone program that could translate text into Morse code. I found a few good online websites, such as the Morse Code Translator 3. However, I was unable to nd a good stand-alone program that could be used to translate text into Morse code independently of an Internet connection. Therefore, I decided to write my own program. This module describes my rst eort in that regard. This document was created using Apache OpenOce Writer 4 and then translated to CNXML suitable for uploading and publishing on OpenStax. 2.1 Viewing tip I recommend that you open another copy of this module in a separate browser window and use the following links to easily nd and view the Figures and Listings while you are reading about them. 2.1.1 Figures Figure 1 (p. 7). The output for HELLO WORLD. 2.1.2 Listings Listing 1 (p. 4). Beginning of the program. Listing 2 (p. 5). Create a hashtable. Listing 3 (p. 6). Begin processing the input data stream. Listing 4 (p. 6). Get the Morse code for the character. Listing 5 (p. 8). Display the character and the code. Listing 6 (p. 9). Convert the Morse code to musical notes. Listing 7 (p. 10). Insert silence between characters. Listing 8 (p. 11). Writing the output le. Listing 9 (p. 12). The program named MorseCodeGenerator01 3 General background information As I also mentioned in the earlier module 5, I was once a radio operator with the U.S. Air Force, mainly using International Morse code. Therefore, Morse code is a topic that I know something about. 2 http://cnx.org/contents/zwwykvgc 3 http://morsecode.scphillips.com/translator.html 4 http://cnx.org/contents/sbe4y4pz:15d17mtn 5 http://cnx.org/contents/zwwykvgc

OpenStax-CNX module: m60489 3 3.1 Historical perspective Before getting into the programming details, however, I will provide some historical perspectives on Morse code. According to Wikipedia 6, "Morse code is a method of transmitting text information as a series of on-o tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment." The "code" was invented by Samuel F. B. Morse around 1836 to describe the characters used in the U.S. telegraph system at the time. The code was later expanded by others to include additional characters. Most people think of the code in terms of dots and dashes. The Wikipedia 7 reference given above contains an image showing the dots and dashes representing what has come to be known as International Morse Code. (Note that there are no lower-case letters in the code.) Although an expanded version of the code includes other characters such as punctuation marks, the program that I will present in this module will deal only with letters, numbers, and the space character. 3.2 Sounds Because of the equipment that was used, the early telegraphers thought of the code in terms of clicks where a dot was represented by two closely spaced clicks and a dash was represented by two clicks spread further apart in time. You may have seen this in movies about the late 1800's. A sailor in the U.S. Navy whose job was and possibly still is to use ashing lights for line-of-sight communication between ships at sea may think of the code in terms of the lengths in time of the ashes. A short ash represents a dot and a longer ash represents a dash. You have probably seen that portrayed in movies about the navy. A radio operator like myself thinks of the code in terms of truncated tones. A dot sounds something like dit and a dash sounds something like dah. Click here 8 to download and play an audio le containing the Morse code for the text HELLO WORLD. (Did it sound like dits and dahs to you?) In the communication facility where I worked, we always used a typewriter to type out the message that we were hearing through the headphones. An experienced operator didn't even think of dits and dahs. Instead, the sounds seemed to go straight from the ears to the ngers pressing the typewriter keys without any thought being given to what was being heard. 3.3 Using previously published code Sometime back, I published a module titled Jbs2060-A Player Piano Simulator 9. If you haven't read that module, I recommend that you read it for context before trying to understand the programming code that I will present later in this module. Note however that the programming code in this module is much less complex than the programming code in the earlier module. You won't need to understand the code in that module in order to understand the code in this module. In brief, the program named MusicComposer09 that I described in that module allows you to dene a text le that represents a melody to be played by the player piano program. (For brevity, I will refer to the player piano program as the PPP in this module.) When the program named MusicComposer09 reads the text le, it plays the melody through the speakers connected to the computer. The approach that I took for the program named M orsecodegenerator01 in this module was straightforward. The program denes a short melody representing the Morse code sounds for each of the numbers from 0 through 9 and each of the letters from A through Z. Then it reads a text le containing a message. For each character in the message, the program sends the appropriate melody to an output le 6 https://en.wikipedia.org/wiki/morse_code 7 https://en.wikipedia.org/wiki/morse_code 8 http://cnx.org/content/m60489/latest/helloworld.au 9 http://cnx.org/contents/27yg7qnc:2qg_6adu

OpenStax-CNX module: m60489 4 concatenating it onto the melodies for each of the previous characters. The result is an output le which, when played by MusicComposer09 produces the Morse code sounds representing the stream of characters in the message. Optionally, those sounds are also recorded in an audio le for playback later. Note that no modications were made to the program named MusicComposer09. As far as that program is concerned, the le produced by M orsecodegenerator01 is just another melody similar to Greensleeves and Mary Had a Little Lamb, although perhaps not as familiar. 3.3.1 How does it sound? To be honest, when I started down this path, I had no idea how the sound of the Morse code melodies produced by this program would compare with the sounds of Morse code created using more conventional techniques such as a key, an oscillator, a radio receiver, etc. However, I am very pleased with the results. The Morse code created using this approach is much cleaner than typical Morse code generated by a human operator using a hand key such as the one shown and identied as a straight key in the article titled Telegraph key 10. By the way, this is the same key that I used in the U.S. Air Force. 4 Discussion and sample code A complete listing of the program is provided in Listing 9 (p. 12) near the end of the lesson. I will break the program down and explain it in fragments. 4.1 Beginning of the program The program begins in Listing 1 (p. 4). Listing 1. Beginning of the program. import java.io.filereader; import java.io.bufferedreader; import java.util.*; public class MorseCodeGenerator01{ public static void main(string[] args){ run(args[0]); }//end main static void run(string inputfile){ //Read the input data String data = readinputfile(inputfile); The code in Listing 1 (p. 4), which shows the main method and the beginning of the run method is routine and should not require an explanation. 4.2 Create a hashtable The run method is continued in Listing 2 (p. 5). The code in Listing 2 (p. 5) is much more interesting than Listing 1 (p. 4). Listing 2 (p. 5) creates a Hashtable object and populates its keys with a space character, the letters of the alphabet, the numbers from 1 through 0, and "error". 10 https://en.wikipedia.org/wiki/telegraph_key

OpenStax-CNX module: m60489 5 Listing 2. Create a hashtable. //Create a hash table containing the codes // for letters, numbers, the space character, // and an error character. Hashtable <String,String>codes = new Hashtable<String,String>(); codes.put(" ","x");//space character codes.put("a","._"); codes.put("b","_..."); codes.put("c","_._."); codes.put("d","_.."); codes.put("e","."); codes.put("f",".._."); codes.put("g","."); codes.put("h","..."); codes.put("i",".."); codes.put("j",". "); codes.put("k","_._"); codes.put("l","._.."); codes.put("m"," "); codes.put("n","_."); codes.put("o"," "); codes.put("p",".."); codes.put("q","._"); codes.put("r","._."); codes.put("s","..."); codes.put("t","_"); codes.put("u",".._"); codes.put("v","..._"); codes.put("w",". "); codes.put("x","_.._"); codes.put("y","_. "); codes.put("z",".."); codes.put("1",". "); codes.put("2",".. "); codes.put("3","... "); codes.put("4","..._"); codes.put("5","..."); codes.put("6","_..."); codes.put("7","..."); codes.put("8",".."); codes.put("9","."); codes.put("0"," "); codes.put("error","..."); With one exception, the hashtable is populated with Morse code values corresponding to the keys. The exception is the value for the key representing the space character. As far as I know, there is no Morse code

OpenStax-CNX module: m60489 6 value for a space character. In Morse code, a space is simply a short period of silence. Therefore, in this program, the value for the space character is "x". This will be interpreted later to indicate that there should be a short period of silence in the output corresponding to each space character in the message. The values for the letters and the numbers are populated with combinations of periods and underscore characters that represent the typical dot-dash patterns for the Morse code for each character. I could have used any two characters for this purpose but the use of dots and dashes made it look more conventional and also made it easier for me to visually check and conrm the accuracy. These combinations of dots and dashes will be used later to create a series of musical notes for each character. All of the musical notes will have the same pitch or frequency (middle C) but will have dierent lengths in time eighth notes, quarter notes, half notes, whole notes, etc. in musical terminology. Finally, the value for the key "error" is populated with eight dots, which is the standard Morse code sound for an error. 4.3 Begin processing the input data stream The code in Listing 3 (p. 6) shows the beginning of a for loop that is used to get and process each character from the input message one character at a time. If a character is a newline character it is skipped. Otherwise, the character is extracted from the input data stream, converted to upper case if needed, and stored in the variable named ch. Listing 3. Begin processing the input data stream. String ch = ""; String code = ""; String sound = ""; for(int cnt = 0;cnt < data.length();cnt++){ //Ignore newline characters. if(!(("" + data.charat(cnt)).equals( "\n"))){ //Convert all input characters to upper // case. ch = ("" + data.charat(cnt)). touppercase(); 4.4 Get the Morse code for the character The code in Listing 4 (p. 6) begins by calling the get method on the hashtable to get the Morse code for the character passed as a key to the method. If there is no key matching the character, the get method returns null. In this case, the Morse code for an error is used to represent the character. This would happen, for example if the message contained a semicolon, which is not a key in the hashtable. Listing 4. Get the Morse code for the character. //Get the code for the input character code = codes.get(ch); //If the input character is not in the

OpenStax-CNX module: m60489 7 // hashtable, transmit an error. if(code == null){ code = codes.get("error"); }//end if 4.5 The output for HELLO WORLD Figure 1 (p. 7) shows the output melody le for the message HELLO WORLD. I will discuss the various parts of the contents of that le in the sections that follow. Figure 1. The output for HELLO WORLD. // x //H... //E. //L._.. //L._.. //O // x //W.

OpenStax-CNX module: m60489 8 //O //R._. //L._.. //D _.. 4.6 Display the character and the code The program code in Listing 5 (p. 8) displays the character and the code in the output le as shown by the rst and fourth lines in Figure 1 (p. 7). A pair of forward slash characters (//) in the output le signies a comment, which is ignored by the PPP that plays the melody. An x in the output le, as shown in Figure 1 (p. 7) and repeated below indicates a space in the input text stream. // x The following line from the output shown in Figure 1 (p. 7) signies the letter H as the rst character in the word HELLO. (The Morse code for the letter "H" is four dots.) //H... Compare this with the line in Listing 2 (p. 5) that shows the key and the value for the key equal to "H". This code could be eliminated with no detrimental impact on the overall performance of the program. It is simply icing on the cake. Listing 5. Display the character and the code. System.out.println("//" + ch + " " + code);

OpenStax-CNX module: m60489 9 4.7 Convert the Morse code to musical notes The code in Listing 6 (p. 9) converts the Morse code for the selected character to a sequence of musical notes. Those notes represent the sound of Morse code for the selected character when the le is played using the PPP. Listing 6. Convert the Morse code to musical notes. for(int ctr = 0; ctr < code.length(); ctr++){ sound = "" + code.charat(ctr); if(sound.equals(".")){ System.out.println(""); }else if(sound.equals("_")){ System.out.println(""); }else if(sound.equals("x")){ System.out.println(""); }//end else if }//end for loop 4.7.1 Interpretation of the programming code This is where some knowledge of the contents of the module titled Jbs2060-A Player Piano Simulator 11 would come in handy. According to International Morse Code 12, "If the duration of a dot is taken to be one unit then that of a dash is three units. The space between the components of one character is one unit, between characters is three units and between words seven units. To indicate that a mistake has been made and for the receiver to delete the last word, send di-di-di-di-di-di-di-dit (eight dots)." Consider the following series of musical notes that represent the letter "L". //L._.. As you can see, the Morse code for this letter has four components, one dot followed by one dash followed by two dots. Thus, there are four musical notes followed by a pause indicated by the "X". The number 1 means to hold the sound of the musical note for one unit in time. The number 3 means to hold the sound for three units in time. The "C4" species the pitch or frequency to be the same as Middle-C on a piano or 261.63 Hz. The "X" at the end means to maintain silence for three units. By taking this approach, it was not necessary for me to deal with the need to maintain one unit of silence between the dots and the dashes. The PPP was designed to make each note distinguishable from the next in a manner similar to the sound that you would hear by pressing a piano key repeatedly. 11 http://cnx.org/contents/27yg7qnc:2qg_6adu 12 http://morsecode.scphillips.com/morse.html

OpenStax-CNX module: m60489 10 4.7.2 One unit of time How much time is represented by one unit of time? This depends on the parameters used when the melody le is played by the PPP. The PPP deals with time in terms of the musical concept of beats. The program allows the user to specify the number of beats per second when playing the melody le. For example, the HELLO WORLD audio le that you downloaded and played earlier (p. 3) was created at eight beats per second. Without getting into the details of the computation, let me just say that experimentally, a string of 100 "E" characters requires about 50 seconds to play at eight beats per second and about 25 seconds to play at 16 beats per second. 4.7.3 Morse code speed Morse code speed is normally discussed in terms of words per minute or WPM. However, it is not clear exactly how speed in WPM is measured. Morse code characters have dierent lengths. Therefore, dierent words will have dierent lengths even if they have the same number of letters. The time required to transmit a message will depend on the words used in the message. One source that I found indicated that WPM is measured using standard ve-letter words such as "PARIS" and "CODEX". I have determined experimentally that when the PPP is set to eight beats per second, six occurrences of the word PARIS followed by six occurrence of the word CODEX require almost exactly one minute to play. This suggests that a PPP rate of eight beats per second produces a Morse code rate of about twelve WPM. (There were no spaces between the words.) This further suggests that clicking here 13 will allow you to download and listen to Morse code at about 12 WPM. 4.7.4 Changing the code speed With this approach, the playback speed in WPM for a given message can be changed by changing the "beats per second" parameter when playing the output melody le with the PPP. For example, increasing that parameter from eight to sixteen beats per second would double the speed of the HELLO WORLD audio le. If you would like to hear what 24 WPM sounds like, click here 14 to download and play an audio le of the same message at twice the speed of the earlier (p. 3) version. 4.8 Insert silence between characters The code in Listing 7 (p. 10) inserts silence for three units of time between message characters. That code also signals the end of the for loop and the end of the run method. Listing 7. Insert silence between characters. System.out.println(""); }//end if on newline }//end for loop }//end run 13 http://cnx.org/content/m60489/latest/helloworld.au 14 http://cnx.org/content/m60489/latest/helloworld16.au

OpenStax-CNX module: m60489 11 4.9 Writing the output le By now, you may be wondering why I used the following Java code to write the output melody le. System.out.println The answer is simply that I did it because it is an easy way to write an output text le containing multiple lines of text. This involves something called output redirection. If you are not familiar with that term, you may want to Google it. Listing 8 (p. 11) contains a Windows batch le that I use to run the program named MorseCodeGenerator01. Listing 8. Writing the output le. echo off del *.class del output.txt javac MorseCodeGenerator01.java java MorseCodeGenerator01 HelloWorld.txt > MorseCodeOutput.txt pause With one possible exception, everything in this batch le should be familiar to you. The le named HelloWorld.txt is the le containing the message that is to be translated into Morse code. The le named MorseCodeOutput.txt is the name of the output le that will contain the melody. Here is the possible exception mentioned above. The "greater than" angle bracket immediately to the left of the output le name instructs the operating system to route all output produced through execution of System.out.println statements in the program to a le with the given name. 4.10 Reading the input le A method named readinputfile is used to read the text message that is to be translated into Morse code. There is nothing unique about that method so I won't discuss it further. You can view the method in its entirety in Listing 9 (p. 12). 5 Run the program I encourage you to copy the code from Listing 9 (p. 12). Create a text message for translation into Morse code. Compile and execute the program using your message le and a batch le similar to the one shown in Listing 8 (p. 11). Then go to Jbs2060-A Player Piano Simulator 15 and follow the instructions to play your Morse code melody le using the PPP. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do. For example, you might want to replace the output redirection with the use of a method to write the output le. Your smart phone probably has a built-in stop watch. Create a text le containing a large number (possibly 100) ve-character groups of random letters and numbers. Think of each group as a "word." Translate the message and create the melody le. Use your timer to measure the amount of time required to play the melody le. Use that information to calculate the speed in WPM. Change the beats per second on playback and play it a few more times. Draw a graph showing the speed in WPM versus beats per second on playback. 15 http://cnx.org/contents/27yg7qnc:2qg_6adu

OpenStax-CNX module: m60489 12 6 Complete program listing A complete listing of the program named MorseCodeGenerator01 is shown in Listing 9 (p. 12) below. Listing 9. The program named MorseCodeGenerator01 /*File MorseCodeGenerator01.java Copyright 2016 R.G.Baldwin 04/28/16 Reads a text file and generates an output file containing musical notes representing Morse code for the characters in the text file. Supports letters, numbers, and the space character. Generates an error code... for each unsupported character in the input text file. Must use output redirection to create the output file as in the following: java MorseCodeGenerator01 in.txt > out.txt The output text file must then be moved to the Music folder to be compatible with the MusicComposer09.java program. ************************************************/ import java.io.filereader; import java.io.bufferedreader; import java.util.*; public class MorseCodeGenerator01{ public static void main(string[] args){ run(args[0]); }//end main static void run(string inputfile){ //Read the input data String data = readinputfile(inputfile); //Create a hash table containing the codes // for letters, numbers, the space character, // and an error character. Hashtable <String,String>codes = new Hashtable<String,String>(); codes.put(" ","x");//space character codes.put("a","._"); codes.put("b","_..."); codes.put("c","_._."); codes.put("d","_.."); codes.put("e",".");

OpenStax-CNX module: m60489 13 codes.put("f",".._."); codes.put("g","."); codes.put("h","..."); codes.put("i",".."); codes.put("j",". "); codes.put("k","_._"); codes.put("l","._.."); codes.put("m"," "); codes.put("n","_."); codes.put("o"," "); codes.put("p",".."); codes.put("q","._"); codes.put("r","._."); codes.put("s","..."); codes.put("t","_"); codes.put("u",".._"); codes.put("v","..._"); codes.put("w",". "); codes.put("x","_.._"); codes.put("y","_. "); codes.put("z",".."); codes.put("1",". "); codes.put("2",".. "); codes.put("3","... "); codes.put("4","..._"); codes.put("5","..."); codes.put("6","_..."); codes.put("7","..."); codes.put("8",".."); codes.put("9","."); codes.put("0"," "); codes.put("error","..."); String ch = ""; String code = ""; String sound = ""; for(int cnt = 0;cnt < data.length();cnt++){ //Ignore newline characters. if(!(("" + data.charat(cnt)).equals( "\n"))){ //Convert all input characters to upper // case. ch = ("" + data.charat(cnt)). touppercase(); //Get the code for the input character code = codes.get(ch); //If the input character is not in the // hashtable, transmit an error. if(code == null){

OpenStax-CNX module: m60489 14 code = codes.get("error"); }//end if //Display the character and the code in // the output file. //An x in the output file indicates a // space in the input text stream. System.out.println("//" + ch + " " + code); //Convert the code to musical notes that // represent Morse code for the character // when the file is played using the // PlayerPiano01 program. for(int ctr = 0; ctr < code.length(); ctr++){ sound = "" + code.charat(ctr); if(sound.equals(".")){ System.out.println(""); }else if(sound.equals("_")){ System.out.println(""); }else if(sound.equals("x")){ System.out.println(""); }//end else if }//end for loop //Insert a short silence between // characters. System.out.println(""); }//end if on newline }//end for loop }//end run //-------------------------------------------// //This method is used to read the input file // containing the message that is to be // translated to Morse code. static String readinputfile(string inputfile){ String pathandfilename = inputfile; String output = ""; String line = ""; try{ FileReader filereader = new FileReader(pathAndFileName); BufferedReader bufferedreader = new BufferedReader(fileReader); while((line = bufferedreader.readline())!= null){ output += line + "\n";

OpenStax-CNX module: m60489 15 }//end while loop filereader.close(); }catch (Exception e) { e.printstacktrace(); }//end catch return output; }//end readinputfile //-------------------------------------------// }//end class MorseCodeGenerator01 //=============================================// 7 Miscellaneous This section contains a variety of miscellaneous information. Housekeeping material Module name: Morse1010 Translating Text to Morse Code File: Morse1010.odt Published: 04/29/16 Disclaimers: Although the OpenStax site makes it possible for you to download a PDF le for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF le, you should be aware that some of the HTML elements in this module may not translate well into PDF. I also want you to know that, I receive no nancial compensation from the OpenStax website even if you purchase the PDF version of the module. In the past, unknown individuals have copied my modules from OpenStax, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on OpenStax and that it was made and published without my prior knowledge. -end