10 Replies - 2054 Views - Last Post: 17 December 2008 - 07:37 AM Rate Topic: -----

#1 meatloaf  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 65
  • Joined: 05-September 07

Lists and Morse Code

Posted 11 December 2008 - 01:46 PM

My program is supposed to take the text the user inputs in the GUIDriver and convert it into Morse code.
The way I have it set up so far is in the MorseCode class, the letters are assigned to their "dits and dahs".
In the GUIDriver, it reads what the user typed and puts each character into a list.
My problem is, how do I compare each character in the "entered" list with all the individual letter variables? Is it possible to add the string variables already declared and making them into a list?
Then, somehow I must compare the two lists, make another list to put in the equaled value of each character, and print in the GUI.

In short:
mainly: How to compare 'entered' list with all the variables
and: how to compare two different lists
and: if character in lists equals, add to new list

Thank you so much!

MorseCode
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import sun.reflect.generics.scope.Scope;

import com.sun.org.apache.xpath.internal.operations.Variable;

// from [url=http://www.nationmaster.com/encyclopedia/Morse-code]http://www.nationmaster.com/encyclopedia/Morse-code[/url]
// from [url=http://en.wikipedia.org/wiki/Morse_code_mnemonics]http://en.wikipedia.org/wiki/Morse_code_mnemonics[/url]
public class MorseCode {
	// private List<MorseCode> entered;

	private final String A = ".- ";
	private final String B = "-... ";
	private final String C = "-.-/>. ";
	private final String D = "-.. ";
	private final String E = ". ";
	private final String F = "..-. ";
	private final String G = "--. ";
	private final String H = ".... ";
	private final String I = ".. ";
	private final String J = ".--- ";
	private final String K = "-.-/> ";
	private final String L = ".-.. ";
	private final String M = "-- ";
	private final String N = "-. ";
	private final String O = "--- ";
	private final String P = ".--. ";
	private final String Q = "--.-/> ";
	private final String R = ".-. ";
	private final String S = "... ";
	private final String T = "- ";
	private final String U = "..- ";
	private final String V = "...- ";
	private final String W = ".-- ";
	private final String X = "-..- ";
	private final String Y = "-.-/>- ";
	private final String Z = "--.. ";
	private final String SPACE = "/ ";
	private final String ZERO = "----- ";
	private final String ONE = ".---- ";
	private final String TWO = "..--- ";
	private final String THREE = "...-- ";
	private final String FOUR = "....- ";
	private final String FIVE = "..... ";
	private final String SIX = "-.... ";
	private final String SEVEN = "--... ";
	private final String EIGHT = "---.. ";
	private final String NINE = "----. ";
	private final String PERIOD = ".-.-/>.- "; 		// .
	private final String COMMA = "--..-- "; 		// ,
	private final String QUESTION = "..--.. "; 		// ?
	private final String EXCLAIM = "..--. "; 		// !
	private final String COLON = "---... "; 		// :
	private final String SEMICOLON = "-.-/>.-. "; 	//;
	private final String QUOTE = ".-..-. "; 		// "
	private final String APOSTROPHE = ".----. ";	// '
	private final String EQUAL = "-...- "; 			// =
	private final String PLUS = ".-.-/>. "; 			// +
	private final String HYPHEN = "-....- "; 		// -
	private final String ASTERISK = "-..- ";		// *
	private final String SLASH = "-..-. "; 			// /
	private final String PARENTHESIS1 = "-.-/>-. "; 	// (
	private final String PARENTHESIS2 = "-.-/>-.- "; 	// )
	private final String UNDERSCORE = "..--.-/> "; 	// _
	private final String AMPERSAND = ".-... "; 		// &
	private final String USDOLLAR = "...-..- "; 	// $
	private final String AT = ".--.-/>. "; 			// @
	

	// public MorseCode(List<String> entered) {
	// myEntered = entered;
	// }

	// [url=http://teatrove.sourceforge.net/javadoc/com/go/tea/compiler/Scope.html]http://teatrove.sourceforge.net/javadoc/co...iler/Scope.html[/url]
//	public Variable[] intersect(Scope scope) {
//		return;
//	}

	public void loadEnteredList(String enteredText) {
		// entered = enteredText.
	}

	public void compareLists() {
		List<MorseCode> complete;
		complete.add(A);
	}

	// read each object in list entered
	// compare to strings
	// if equals, put string in new list
	// print in label
}



MorseCodeGUIDriver
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import ann.gui.CloseableFrame;

public class MorseCodeGUIDriver extends CloseableFrame implements
		ActionListener {

	private JLabel messageLabel, resultLabel;
	private JTextField resultField;
	private JButton convertButton, exitButton;
	private JPanel myResultPanel;
	private MorseCode morse;

	private String enteredText;

	public MorseCodeGUIDriver() {
		setTitle("Morse Code : -- --- .-. ... . / -.-/>. --- -.. .");
		messageLabel = new JLabel(
				"Type in text you want converted to Morse code: ");
		resultLabel = new JLabel("");
		convertButton = new JButton("Convert");
		convertButton.addActionListener(this);
		exitButton = new JButton("Exit");
		exitButton.addActionListener(this);
		resultField = new JTextField(50);
		resultField.setEditable(true);
		setLayout(new FlowLayout());
		add(messageLabel);
		add(resultField);
		add(convertButton);
		add(exitButton);
		myResultPanel = new JPanel(new BorderLayout());
		myResultPanel.add(resultLabel, BorderLayout.CENTER);
//		setContentPane(myResultPanel);
		morse = new MorseCode();
	}

	public void actionPerformed(ActionEvent e) {
		char letter;
		List<MorseCode> entered = new ArrayList<MorseCode>();
		String enteredText = resultField.getText();
		for (int i = 0;i > entered.size(); i++) {
			letter = enteredText.charAt(i);
			entered.add(letter);
		}
//		String list = String.valueOf(letter);
		// List<String> en = String.toString(enteredText);
		// resultField.setText(en);
		if (e.getActionCommand().equals("Convert"))
			morse.compareLists();
		else if (e.getActionCommand().equals("Exit"))
			System.exit(0);
		
//		double result = calculator.apply(operator);
//		String enteredText = Double.toString(result);
//		resultField.setText(enteredText);
	}

	public static void main(String[] args) {
		// This main method creates and starts the GUI driver object.
		MorseCodeGUIDriver gui = new MorseCodeGUIDriver();
		gui.pack();
		gui.setVisible(true);
	}
}


This post has been edited by Programmist: 11 December 2008 - 07:42 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Lists and Morse Code

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Lists and Morse Code

Posted 11 December 2008 - 09:16 PM

Hey hey cute problem :D

Use one big String to define the letter/code and one array of String[] for the corresponding Morse code and then just loop through the inputed String

String supportedDigit = "ABCDEF...XYZ 1234567890...";
String[] morse = {".-", "-...", "-.-/>.", "-..".......};

String str = "Hello World";
str = str.toUpperCase();	   // Morse does not have lower/upper

// extract every digits from the inputed string
for(int i = 0; i < str.length; i++) {
   // extract the character
   char digit = str.charAt(i);
   // scan the supported digits
   for(int j = 0; j < supportedDigit.length; j++) {
	   // test if they match
	   if(digit == supportedDigit.charAt(j)) {
			// found Morse is morse[j];  do what you have to do
			break;   // done no need to continue
	   }
}


Was This Post Helpful? 0
  • +
  • -

#3 Programmist  Icon User is offline

  • Refactorer in Chief
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,843
  • Joined: 02-January 06

Re: Lists and Morse Code

Posted 11 December 2008 - 09:19 PM

No one has answered this one, so I'll give you a hint. A very simple way to do this would be to use a Map<Character,String>, rather than a bunch of variables. If you do it this way you'll want to make sure you normalize the case of each character you read in from the user, so that you don't have redundant upper and lower case keys (e.g. 'a' --> ".-" and 'A' --> ".-").
Was This Post Helpful? 0
  • +
  • -

#4 Programmist  Icon User is offline

  • Refactorer in Chief
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,843
  • Joined: 02-January 06

Re: Lists and Morse Code

Posted 11 December 2008 - 09:40 PM

Edit: looks like someone beat me to it by three minutes. :)

Incidentally, however, HashMap lookups take O(1) time so as the size of the input string grows, you'll find a linear array search (as pbl uses) will be significantly slower. But it will work.
Was This Post Helpful? 0
  • +
  • -

#5 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Lists and Morse Code

Posted 11 December 2008 - 11:42 PM

Picking up on what pbl suggested, make a string array of your Morse code strings. Also make a string of the symbols the first array encodes. Make sure there is a one-to one correspondence between the two. That is, the Morse code string THREE is at the same place in the morse[] array as the character '3' is in the supportedDigit[] string. (I prefer the name supportedSymbol but that's just me :)

Now converting the characters to their Morse code equivalents is a simple indexed operation:
...
// For every symbol in the supportedSymbol string there must be a corresponding Morse code string at the same index in the morse[] array.
String supportedSymbol = "ABCDEF...XYZ 1234567890...";
String[] morse = {".-", "-...", "-.-/>.", "-..".......};

StringBuilder CodeString = new StringBuilder();

enteredText = enteredText.toUpperCase();

int index = 0;

for (int i = 0; i < enteredText.length(); i++) {
	char ch = enteredText.charAt(i);

	if ((index = supportedSymbol.indexOf(ch)) < 0) {
		continue;  // ch is not in array
	}

	CodeString.append(morse[index]);
}
...


This post has been edited by n8wxs: 11 December 2008 - 11:46 PM

Was This Post Helpful? 0
  • +
  • -

#6 Programmist  Icon User is offline

  • Refactorer in Chief
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,843
  • Joined: 02-January 06

Re: Lists and Morse Code

Posted 12 December 2008 - 07:10 AM

Using the String indexOf method in this case is identical to using the linear array search pbl used. The only benefit you are gaining is that you are reusing code, but the time deficit between this method and using a HashMap is still the same. It's O(n) vs O(1) and the HashMap wins.

Something else - when you use a map it's more maintainable. You don't have to maintain two arrays and worry about keeping the indicies of symbols and corresponding Morse code strings the same.

And if you want to be even more slick, you could put the symbols and corresponding Morse code strings in a Properties file and load them into your map at run time. That way you don't have to recompile if you want to add more symbols.
Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8378
  • View blog
  • Posts: 31,956
  • Joined: 06-March 08

Re: Lists and Morse Code

Posted 12 December 2008 - 08:56 PM

View PostProgrammist, on 12 Dec, 2008 - 06:10 AM, said:

Using the String indexOf method in this case is identical to using the linear array search pbl used. The only benefit you are gaining is that you are reusing code, but the time deficit between this method and using a HashMap is still the same. It's O(n) vs O(1) and the HashMap wins.

Something else - when you use a map it's more maintainable. You don't have to maintain two arrays and worry about keeping the indicies of symbols and corresponding Morse code strings the same.

And if you want to be even more slick, you could put the symbols and corresponding Morse code strings in a Properties file and load them into your map at run time. That way you don't have to recompile if you want to add more symbols.

Sorry I was tryng to respond to a newbie question who probably does not have a clue of what an Hashmap is
Is I had been really picky I would have made Morse object containing "-" and "." and associated them with AlphabeticalObjects
64 constructors would habe been provided to create a MorseObject
new Morse(dot)
new Morse(dot, dash)
new Morse(dot, dot)
...
seriously... I was trying to fix a newbie problem with his Java knowledge and I think that base on the "basic" question... Hashmap was not in his horizons (no insult at all MeatLoaf.. you are in a learning curve and this is normal)
Was This Post Helpful? 0
  • +
  • -

#8 meatloaf  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 65
  • Joined: 05-September 07

Re: Lists and Morse Code

Posted 13 December 2008 - 01:21 AM

Thank you all for your suggestions. I will get back to you on what I come up with! :D
Was This Post Helpful? 0
  • +
  • -

#9 Programmist  Icon User is offline

  • Refactorer in Chief
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,843
  • Joined: 02-January 06

Re: Lists and Morse Code

Posted 13 December 2008 - 07:00 AM

View Postpbl, on 12 Dec, 2008 - 08:56 PM, said:

seriously... I was trying to fix a newbie problem with his Java knowledge and I think that base on the "basic" question... Hashmap was not in his horizons (no insult at all MeatLoaf.. you are in a learning curve and this is normal)

I understand. However, I would not have made the assumption that he was a newbie or that, if he was, that he could not figure out how to use maps or not be able to ask questions if he was confused. But now he has two solutions. :) So if he is a total newbie then I've just broadened his horizons by introducing him to the map data structure. Even if he doesn't use it in his problem maybe he'll be curious and go read more about it.
Was This Post Helpful? 0
  • +
  • -

#10 meatloaf  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 65
  • Joined: 05-September 07

Re: Lists and Morse Code

Posted 15 December 2008 - 09:07 PM

I DID look those things up and will try them some other time, but just to get things going, I made a modified code.

It works fine now. My next question is how could I get it to play?
There is already a string with the ".", "-", "/", and " " called print.

MorseCode:
package edu.calvin.amw28.hotj.finalproject;

/**
 * This class holds the conversions of the characters to the string.
 * 
 * Information confirmed by: www.nationmaster.com/encyclopedia/Morse-code
 * www.nationmaster.com/encyclopedia/Morse-code
 * 
 * @author meatloaf
 * @version Final Project 12.16.08
 */
public class MorseCode {

	/**
	 * Constructor method
	 */
	public MorseCode() {

	}

	/**
	 * Constructor method with a switch case comparing values.
	 * 
	 * @param letter
	 */
	public String convert(char letter) {
		switch (letter) {
		case 'A':
			return ".- ";
		case 'B':
			return "-... ";
		case 'C':
			return "-.-/>. ";
		case 'D':
			return "-.. ";
		case 'E':
			return ". ";
		case 'F':
			return "..-. ";
		case 'G':
			return "--. ";
		case 'H':
			return ".... ";
		case 'I':
			return ".. ";
		case 'J':
			return ".--- ";
		case 'K':
			return "-.-/> ";
		case 'L':
			return ".-.. ";
		case 'M':
			return "-- ";
		case 'N':
			return "-. ";
		case 'O':
			return "--- ";
		case 'P':
			return ".--. ";
		case 'Q':
			return "--.-/> ";
		case 'R':
			return ".-. ";
		case 'S':
			return "... ";
		case 'T':
			return "- ";
		case 'U':
			return "..- ";
		case 'V':
			return "...- ";
		case 'W':
			return ".-- ";
		case 'X':
			return "-..- ";
		case 'Y':
			return "-.-/>- ";
		case 'Z':
			return "--.. ";
		case ' ':
			return "/ ";
		case '0':
			return "----- ";
		case '1':
			return ".---- ";
		case '2':
			return "..--- ";
		case '3':
			return "...-- ";
		case '4':
			return "....- ";
		case '5':
			return "..... ";
		case '6':
			return "-.... ";
		case '7':
			return "--... ";
		case '8':
			return "---.. ";
		case '9':
			return "----. ";
		case '.':
			return ".-.-/>.- "; // .
		case ',':
			return "--..-- "; // ,
		case '?':
			return "..--.. "; // ?
		case '!':
			return "..--. "; // !
		case ':':
			return "---... "; // :
		case ';':
			return "-.-/>.-. "; //;
		case '"':
			return ".-..-. "; // "
		// case ''': return ".----. "; // '
		case '=':
			return "-...- "; // =
		case '+':
			return ".-.-/>. "; // +
		case '-':
			return "-....- "; // -
		case '*':
			return "-..- "; // *
		case '/':
			return "-..-. "; // /
		case '(':
			return "-.-/>-. "; // (
		case ')':
			return "-.-/>-.- "; // )
		case '_':
			return "..--.-/> "; // _
		case '&':
			return ".-... "; // &
		case '$':
			return "...-..- "; // $
		case '@':
			return ".--.-/>. "; // @
		}
		return "? "; // unlisted char
	}
}



MorseCodeGUIDriver:
package edu.calvin.amw28.hotj.finalproject;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import ann.gui.CloseableFrame;
//import ann.midi.Midi;
//import ann.midi.MidiPlayer;

/**
 * MorseCodeGUIDriver is the graphic driver program that displays Morse code
 * converted from the user's input.
 * 
 * @author meatloaf
 * @version Final Project 12.16.08
 */
public class MorseCodeGUIDriver extends CloseableFrame implements
		ActionListener {
	private static final long serialVersionUID = 1L;
	private JLabel messageLabel, resultLabel;
	private JTextField resultField;
	private JButton convertButton, exitButton;
	private JPanel myResultPanel, myMainPanel;
	private MorseCode morse;
	// private String enteredText;
	
	/**
	 * Construction method of GUI.
	 */
	public MorseCodeGUIDriver() {
		setTitle("Morse Code : -- --- .-. ... . / -.-/>. --- -.. .");
		messageLabel = new JLabel(
				"Type in text you want converted to Morse code: ");
		resultLabel = new JLabel(" ");
		resultField = new JTextField(20);
		resultField.setEditable(false);
		convertButton = new JButton("Convert");
		convertButton.addActionListener(this);
		exitButton = new JButton("Exit");
		exitButton.addActionListener(this);
		resultField = new JTextField(45);
		resultField.setEditable(true);
		setLayout(new FlowLayout());
		myMainPanel = new JPanel(new FlowLayout());
		myMainPanel.add(messageLabel);
		myMainPanel.add(resultField);
		myMainPanel.add(convertButton);
		myMainPanel.add(exitButton);
		myMainPanel.add(resultLabel);
		setLayout(new BorderLayout());
		myResultPanel = new JPanel(new BorderLayout());
		myResultPanel.add(myMainPanel, BorderLayout.NORTH);
		myResultPanel.add(resultLabel, BorderLayout.SOUTH);
		setContentPane(myResultPanel);
		morse = new MorseCode();
	}

	/**
	 * ActionEvent handler 
	 * Receive: event, an ActionEvent 
	 * Precondition: event was generated by exitButton or convertButton 
	 * Postcondition: event has been processed
	 */
	public void actionPerformed(ActionEvent e) {
		// List<String> entered = new ArrayList<String>();
		String supportedLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789.,?!:;'=+-*/()_&$@";
		String str = resultField.getText();
		String result = "";
		String print = " ";
		str = str.toUpperCase();

		if (e.getActionCommand().equals("Convert")) {
			for (int i = 0; i < str.length(); i++) {
				char letter = str.charAt(i);
				for (int j = 0; j < supportedLetter.length(); j++) {
					if (letter == supportedLetter.charAt(j)) {
						result = morse.convert(letter);
						print = print + result;
					}
				}
			}
			resultLabel.setText(print);
		} else if (e.getActionCommand().equals("Exit"))
			System.exit(0);
	}

	/**
	 * This main method creates and starts the GUI driver object
	 */
	public static void main(String[] args) {
		MorseCodeGUIDriver gui = new MorseCodeGUIDriver();
		gui.pack();
		gui.setVisible(true);
//
//		try {
//			MidiPlayer midi = new MidiPlayer();
//			exercise1(midi);
//			midi.close();
//		} catch (Exception e) {
//			// Print a trace of any error that may happen in any exercise
//			e.printStackTrace();
//		}
	}
//
//	public static void exercise1(MidiPlayer midi) throws InterruptedException,
//			NullPointerException {
//		/**
//		 * String Tokenizer method
//		 */
//		midi = new MidiPlayer();
//		midi.setInstrument(Midi.C4);
//	}
}



Part (my sad attempt to make noise):
package edu.calvin.amw28.hotj.finalproject;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import ann.midi.Beat;
import ann.midi.Event;
import ann.midi.Midi;

// from Chord
public class Length {
	private final int DIT_DURATION = 250;
	private final int DA_DURATION = 500;
	private final int SPACE_DURATION = 250;
	private final int SLASH_DURATION = 0;
	private final int myPitch = 100;
	private final int myVelocity = 100;
	List<Beat> myD = new ArrayList<Beat>();

	public List<Event> getEvents(int eventType) {
		List<Event> events = new ArrayList<Event>();
		for(int pitch : myPitch) {
			events.add( new Event(eventType, myPitch, myVelocity));
		}
		return events;
//		new Event(eventType, pitch, myVelocity);
	}
	
	// if char in print equals "." or "-" or " " or "/", play
	public void play(String print) {
		char printDit = '.';
		char printDa = '-';
		char printSp = ' ';
		char printSl = '/';
		char digit = ' ';
		for (int i = 0; i < print.length(); i++) {
			digit = print.charAt(i);
			if (printDit == digit)
				myD.add(DIT_DURATION);
			else if (printDa == digit)
				myD.add(DA_DURATION);
			else if (printSp == digit)
				myD.add(SPACE_DURATION);
			else if (printSl == digit)
				myD.add(SLASH_DURATION);
		}
	}
	// public Event getEvent(int eventType) {
	// return new Event(eventType, myPitch, myVelocity);
	// }

	// public Length(String chordLine) {
	// // Auto-generated constructor stub
	// }

	// public List<Event> getEvents(int eventType) {
	// List<Event> events = new ArrayList<Event>();
	// for (int pitch : myD) {
	// // events.add(new Event(eventType, pitch, myVelocity));
	// }
	// return events;
	// // new Event(eventType, pitch, myVelocity);
	// }

	// //reading from files
	// public Length(String line) throws NullPointerException {
	// StringTokenizer tokenizer = new StringTokenizer(line);
	//
	// while (tokenizer.hasMoreTokens()) {
	// // myDuration = Midi.parseDuration(tokenizer.nextToken());
	// // // myPitch1 = Midi.parsePitch(tokenizer.nextToken());
	// // // myPitch2 = Midi.parsePitch(tokenizer.nextToken());
	// while (tokenizer.hasMoreTokens()) {
	// // // myPitches.add(tokenizer.nextToken());
	// // myPitches.add( Midi.parsePitch(tokenizer.nextToken()));
	// }
	// // myVelocity = DEFAULT_VELOCITY;
	// }
	// }
}


:rolleyes:
btw, the correct pronoun is "she".

This post has been edited by macosxnerd101: 16 August 2010 - 11:51 AM

Was This Post Helpful? 0
  • +
  • -

#11 Programmist  Icon User is offline

  • Refactorer in Chief
  • member icon

Reputation: 255
  • View blog
  • Posts: 1,843
  • Joined: 02-January 06

Re: Lists and Morse Code

Posted 17 December 2008 - 07:37 AM

View Postmeatloaf, on 15 Dec, 2008 - 09:07 PM, said:

:rolleyes:
btw, the correct pronoun is "she".

I had no way of knowing that. If you really cared then you probably should have put your gender in your profile or pick a handle that is a little more feminine.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1