Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Morse Code (Schleifen)

Schreiben Sie ein Programm, das einen Text ins Morsealphabet umwandeln kann. Der Anwender kann den Text selbst wählen.

Die Symbole sollen mit Punkt (·) bzw. Minuszeichen (-) dargestellt werden. Zwischen zwei Buchstaben soll ein Leerzeichen ( ), zwischen zwei Wörtern sollen drei Leerzeichen (   ) stehen.

Für das Morsealphabet bitte hier nachschlagen:

de.wikipedia.org/wiki/Morsecode

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

13 Lösung(en)

package ch.programmieraufgaben.strings.morse;

import java.util.*;

/**
 * Verwandle eine Zeichenkette in das Morsealphabet
 * @author Philipp Gressly (phi AT gressly DOT ch)
 */
public class MorseCode {

  public static void main(String[] args) {
    new MorseCode().top();
  }

  Map<Character, String> morseCode = new HashMap<Character, String>(64);
    
  void top() {
    initialisiereMorseCode();
    String eingabe = einlesen("lesbaren Text");
    String codiert = morse(eingabe);
    System.out.println("Morsecode: " + codiert);
  }
    
    
  void initialisiereMorseCode() {
    morseCode.put('A', "·-");
    morseCode.put('B', "-···");
    morseCode.put('C', "-·-·");
    morseCode.put('D', "-··");
    morseCode.put('E', "·");
    morseCode.put('F', "··-·"); 
    morseCode.put('G', "--·");
    morseCode.put('H', "····");
    morseCode.put('I', "··");
    morseCode.put('J', "·---");
    morseCode.put('K', "-·-");
    morseCode.put('L', "·-··"); 
    morseCode.put('M', "--");
    morseCode.put('N', "-·");
    morseCode.put('O', "---");
    morseCode.put('P', "·--·");
    morseCode.put('Q', "--·-");
    morseCode.put('R', "·-·");
    morseCode.put('S', "···"); 
    morseCode.put('T', "-");
    morseCode.put('U', "··-");
    morseCode.put('V', "···-");
    morseCode.put('W', "·--");
    morseCode.put('X', "-··-");
    morseCode.put('Y', "-·--"); 
    morseCode.put('Z', "--··");
       
    morseCode.put('0', "-----");
    morseCode.put('1', "·----");
    morseCode.put('2', "··---"); 
    morseCode.put('3', "···--");
    morseCode.put('4', "····-");
    morseCode.put('5', "·····");
    morseCode.put('6', "-····");
    morseCode.put('7', "--···");
    morseCode.put('8', "---··"); 
    morseCode.put('9', "----·");
     
    morseCode.put('Ä', "·-·-");
    morseCode.put('Ö', "---·");
    morseCode.put('Ü', "··--"); 
    morseCode.put('ß', "···--··");
     
    morseCode.put('.', "·-·-·-");
    morseCode.put(',', "--··--");
    morseCode.put('?', "··--··"); 
    morseCode.put('@', "·--·-·");
  }
    
  String morse(String eingabe) {
    StringBuffer morse = new StringBuffer();
    for(char c : eingabe.toUpperCase().toCharArray()) {
      if(' ' == c) {
        morse.append("   "); // Wortzwischenraum
      } else {
        String m = morseCode.get(c);
        if(null != m) {
          morse.append(morseCode.get(c));
          morse.append(" "); // Buchstabenzwischenraum
        }
      }
    }
    return morse.toString().trim(); 
  }

  Scanner sc = new Scanner(System.in);
  String einlesen(String frage) {
    System.out.println("Bitte " + frage + " eingeben: ");
    return sc.nextLine();
  }

}// end of class MorseCode
                

Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

// Autor:				Andy Großhennig
// Solution for task:	Morse Code (Schleifen)

#include <iostream>

using namespace std;

// Function: Format message in morse code
string format(string sInput)
{
	string sOutput;

	// Loop: Read one by one and form in morse code as the text is long
	for(int i = 0;i < sInput._Mysize;i++)
	{
		switch(sInput[i])
		{
			case ' ': sOutput += "   ";
				break;
			case 'a': sOutput += ".- ";
				break;
			case 'b': sOutput += "-... ";
				break;
			case 'c': sOutput += "-.-. ";
				break;
			case 'd': sOutput += "-.. ";
				break;
			case 'e': sOutput += ". ";
				break;
			case 'f': sOutput += "..-. ";
				break;
			case 'g': sOutput += "--. ";
				break;
			case 'h': sOutput += ".... ";
				break;
			case 'i': sOutput += ".. ";
				break;
			case 'j': sOutput += ".--- ";
				break;
			case 'k': sOutput += "-.- ";
				break;
			case 'l': sOutput += ".-.. ";
				break;
			case 'm': sOutput += "-- ";
				break;
			case 'n': sOutput += "-. ";
				break;
			case 'o': sOutput += "--- ";
				break;
			case 'p': sOutput += ".--. ";
				break;
			case 'q': sOutput += "--.-";
				break;
			case 'r': sOutput += ".-. ";
				break;
			case 's': sOutput += "... ";
				break;
			case 't': sOutput += "- ";
				break;
			case 'u': sOutput += "..- ";
				break;
			case 'v': sOutput += "...- ";
				break;
			case 'w': sOutput += ".-- ";
				break;
			case 'x': sOutput += "-..- ";
				break;
			case 'y': sOutput += "-.-- ";
				break;
			case 'z': sOutput += "--.. ";
				break;
			case '0': sOutput += "----- ";
				break;
			case '1': sOutput += ".---- ";
				break;
			case '2': sOutput += "..--- ";
				break;
			case '3': sOutput += "...-- ";
				break;
			case '4': sOutput += "....- ";
				break;
			case '5': sOutput += "..... ";
				break;
			case '6': sOutput += "-.... ";
				break;
			case '7': sOutput += "--... ";
				break;
			case '8': sOutput += "---.. ";
				break;
			case '9': sOutput += "----. ";
				break;
			default: break;
		}
	}

	return sOutput;
}

// Function: Get the text and show it in morse code
void ioStream()
{
	string sInput, sOutput;

	cout << "Nachricht zur Umwandlung in Morsecode eingeben (nur a - z und 0 - 9). \n";
	getline(cin, sInput);

	sOutput = format(sInput);

	cout << endl << sOutput << endl;
}

int main()
{
	ioStream();

	cout << "\n\n";
	system("Pause");
	return 0;
}
                

Lösung von: Andy Großhennig (Bundeswehr)

#include <stdio.h>

#include <string.h>


// converts ascii-characters into morse code

void ascii_to_morse(char character)
{
    switch(character)
    {

        // letters

        case 'a':
        case 'A':
            printf(".- ");
            break;

        case 'b':
        case 'B':
            printf("-... ");
            break;

        case 'c':
        case 'C':
            printf("-.-. ");
            break;

        case 'd':
        case 'D':
            printf("-.. ");
            break;

        case 'e':
        case 'E':
            printf(". ");
            break;

        case 'f':
        case 'F':
            printf("..-. ");
            break;

        case 'g':
        case 'G':
            printf("--. ");
            break;

        case 'h':
        case 'H':
            printf(".... ");
            break;

        case 'i':
        case 'I':
            printf(".. ");
            break;

        case 'j':
        case 'J':
            printf(".--- ");
            break;

        case 'k':
        case 'K':
            printf("-.- ");
            break;

        case 'l':
        case 'L':
            printf(".-.. ");
            break;

        case 'm':
        case 'M':
            printf("-- ");
            break;

        case 'n':
        case 'N':
            printf("-. ");
            break;

        case 'o':
        case 'O':
            printf("--- ");
            break;

        case 'p':
        case 'P':
            printf(".--. ");
            break;

        case 'q':
        case 'Q':
            printf("--.- ");
            break;

        case 'r':
        case 'R':
            printf(".-. ");
            break;

        case 's':
        case 'S':
            printf("... ");
            break;

        case 't':
        case 'T':
            printf("- ");
            break;

        case 'u':
        case 'U':
            printf("..- ");
            break;

        case 'v':
        case 'V':
            printf("...- ");
            break;

        case 'w':
        case 'W':
            printf(".-- ");
            break;

        case 'x':
        case 'X':
            printf("-..- ");
            break;

        case 'y':
        case 'Y':
            printf("-.-- ");
            break;

        case 'z':
        case 'Z':
            printf("--.. ");
            break;



        // spaces

        case ' ':
            printf("  ");
            break;



        // numbers

        case '0':
            printf("----- ");
            break;

        case '1':
            printf(".---- ");
            break;

        case '2':
            printf("..--- ");
            break;

        case '3':
            printf("...-- ");
            break;

        case '4':
            printf("....- ");
            break;

        case '5':
            printf("..... ");
            break;

        case '6':
            printf("....- ");
            break;

        case '7':
            printf("...-- ");
            break;

        case '8':
            printf("..--- ");
            break;

        case '9':
            printf(".---- ");
            break;



        // punctuation marks

        case '.':
            printf(".-.-.- ");
            break;

        case ',':
            printf("--..-- ");
            break;

        case ':':
            printf("---... ");
            break;

        case ';':
            printf("-.-.-. ");
            break;

        case '?':
            printf("..--.. ");
            break;

        case '-':
            printf("-....- ");
            break;

        case '_':
            printf("..--.- ");
            break;

        case '(':
            printf("-.--. ");
            break;

        case ')':
            printf("-.--.- ");
            break;

        case '\'':
            printf(".----. ");
            break;

        case '=':
            printf("-...- ");
            break;

        case '+':
            printf(".-.-. ");
            break;

        case '/':
            printf("-..-. ");
            break;

        case '@':
            printf(".--.-. ");
            break;



        // special characters

        case 1:
            printf(".-.- ");
            break;

        case 2:
            printf("---. ");
            break;

        case 3:
            printf("..--- ");
            break;

        case 4:
            printf("---- ");
            break;

        case 5:
            printf("...--.. ");
            break;



        default:
            printf("........ ");

    }
}


// checks if there is a Ä, Ö, Ü, CH or ß

int check_special_character(char string[], int position)
{
    if(string[position] == 'A' || string[position] == 'a')
        if(string[position+1] == 'E' || string[position+1] == 'e')
            return 1;

    if(string[position] == 'O' || string[position] == 'o')
        if(string[position+1] == 'E' || string[position+1] == 'e')
            return 2;

    if(string[position] == 'U' || string[position] == 'u')
        if(string[position+1] == 'E' || string[position+1] == 'e')
            return 3;

    if(string[position] == 'C' || string[position] == 'c')
        if(string[position+1] == 'H' || string[position+1] == 'h')
            return 4;

    if(string[position] == 'S' || string[position] == 's')
        if(string[position+1] == 'S' || string[position+1] == 's')
            return 5;

    return 0;
}


// main translation function

void translate_to_morse(char text[])
{
    int length = strlen(text);
    int special;
    int i;
    char character;

    for(i = 0; i < length; i++)     // translation loop
    {
        character = 0;

        if(!(i+1 == length))
            special = check_special_character(text, i);     // checks special characters
        else
            special = 0;

        if(special != 0)                                    // handles special characters
        {
            character = special;
            length--;
            i++;
        }

        if(character == 0)                                  // handles non-special characters
            character = text[i];

        ascii_to_morse(character);                          // converts characters to morse code

    }
}


int main()
{
    char text[100];

    printf("Geben sie den Text ein (um zu Beenden drücken sie Enter):\n");
    fgets(text, sizeof(text), stdin);          // reading in the text
    text[strlen(text)-1] = '\0';                  // cutting off the \n

    printf("\n");

    translate_to_morse(text);               // main translation function

	return 0;
}

                

Lösung von: Peter Hösch (Keine/Privat)

/**
 * @autor   philipp gressly freimann
 * @verison 1.0 15. Okt. 2013
 * Programmierübung "Morse" Web Code:0bgw-abqq
 * Programmiert in Wiring (Processing based)
 */
 
// PIN 13 is onboard LED 
#define led13 13

// Define BAUD-Rate for Serial reading:
#define BAUD_RATE 9600

void setup() {                
  // initialize the Diode as an output.
  pinMode(led13, OUTPUT); 

  // init for reading via USB
  Serial.begin(BAUD_RATE);
}

// Initialize MORSE lengths
int dotLength  =  200; // Morse dot  (.)
int lineLength =  550; // Morse line (-)
int smallGap   =   90; // Gap between dots and lines
int letterGap  =  500; // Gap between two letters
int wordGap    = 1000; // Gap between two words


// the loop routine runs over and over again forever:
void loop() {
  if(Serial) {
    int inputByte = Serial.read();
    if(inputByte > 0) {
      letter((char) inputByte);
    }
  }
}

void letter(char c) {
  String lineDots = "";
  
  if(' ' == c) {  wordPause(); return; }

  // make c lowercase
  String cString = String(c);
  cString.toLowerCase();
  c = cString[0];
  
  if('a'  == c) { lineDots = ".-"    ; } else
  if('b'  == c) { lineDots = "-..."  ; } else
  if('c'  == c) { lineDots = "-.-."  ; } else
  if('d'  == c) { lineDots = "-.."   ; } else
  if('e'  == c) { lineDots = "."     ; } else
  if('f'  == c) { lineDots = "..-."  ; } else
  if('g'  == c) { lineDots = "--."   ; } else
  if('h'  == c) { lineDots = "...."  ; } else
  if('i'  == c) { lineDots = ".."    ; } else
  if('j'  == c) { lineDots = ".---"  ; } else
  if('k'  == c) { lineDots = "-.-"   ; } else
  if('l'  == c) { lineDots = ".-.."  ; } else
  if('m'  == c) { lineDots = "--"    ; } else
  if('n'  == c) { lineDots = "-."    ; } else
  if('o'  == c) { lineDots = "---"   ; } else
  if('p'  == c) { lineDots = ".--."  ; } else
  if('q'  == c) { lineDots = "--.-"  ; } else
  if('r'  == c) { lineDots = ".-."   ; } else
  if('s'  == c) { lineDots = "..."   ; } else
  if('t'  == c) { lineDots = "-"     ; } else
  if('u'  == c) { lineDots = "..-"   ; } else
  if('v'  == c) { lineDots = "...-"  ; } else
  if('w'  == c) { lineDots = ".--"   ; } else
  if('x'  == c) { lineDots = "-..-"  ; } else
  if('y'  == c) { lineDots = "-.--"  ; } else
  if('z'  == c) { lineDots = "--.."  ; } else

  if('0'  == c) { lineDots = "-----" ; } else
  if('1'  == c) { lineDots = ".----" ; } else
  if('2'  == c) { lineDots = "..---" ; } else
  if('3'  == c) { lineDots = "...--" ; } else
  if('4'  == c) { lineDots = "....-" ; } else
  if('5'  == c) { lineDots = "....." ; } else
  if('6'  == c) { lineDots = "-...." ; } else
  if('7'  == c) { lineDots = "--..." ; } else
  if('8'  == c) { lineDots = "---.." ; } else
  if('9'  == c) { lineDots = "----." ; } else

  if('.'  == c) { lineDots = ".-.-.-"; } else
  if(','  == c) { lineDots = "--..--"; } else
  if('?'  == c) { lineDots = "..--.."; } else
  if('!'  == c) { lineDots = "..--." ; } else
  if(':'  == c) { lineDots = "---..."; } else
  if('\"' == c) { lineDots = ".-..-."; } else
  if('\'' == c) { lineDots = ".----."; } else
  if('='  == c) { lineDots = "-...-" ; } 

  for(int i = 0; i < lineDots.length(); i++) {
    char ld = lineDots.charAt(i);
    if('-' == ld) {
      line();
    } else
    if('.' == ld) {
      dot();
    }
  }
  letterPause();
}

void wordPause() {
  blinkOnce(0, wordGap);
}

void letterPause() { 
  blinkOnce(0, letterGap);
}

// make a short morse dot (.)
void dot() {
  blinkOnce(dotLength, smallGap);
}

// make a longer more line (-)
void line() {
  blinkOnce(lineLength, smallGap);
}

/**
 * amount blinking time in ms
 * gap    off-time in ms
 */
void blinkOnce(int amount, int gap) {
  if(amount > 0) {
    digitalWrite(led13, HIGH);  // ON
    delay(amount);              // Stay on
  }    
  digitalWrite(led13, LOW);     // OFF
  delay(gap);                   // wait for a given gap (ms)
}


                

Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

import java.util.Scanner;

public class morsecode {

    // Stringarray das die möglichen Buchstaben und deren Übersetzung enthällt
    private String[][] morsearray = new String[][] { { "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", "-----" },

	    { "?", "..--.." }, { "Ö", "---." }, { "Ü", "..--" },
	    { "Ä", ".-.-" }, { ".", ".-.-.-" }, { ",", "--..--" },
	    { " ", "  " } };

    // wandelt die Eingabe in Morsecode um
    private String zuMorseUmwandeln(String eingabe) {

	String ausgabe = ""; // enthällt am ende den Morsecode

	char[] c = eingabe.toUpperCase().toCharArray(); // Eingabe als Chararray

	int morsekey = 0; // Stelle an der der Buchstabe im Array steht

	/*
	 * Sucht den Buchstaben im Array, nimmt dann dessen Übersetzung und fügt
	 * diese dem String hinzu
	 */
	for (int i = 0; i < c.length; i++) {

	    for (int o = 0; o < morsearray.length; o++) {
		if (String.valueOf(c[i]).equals(morsearray[o][0])) {
		    morsekey = o;
		    break;
		}
	    }

	    ausgabe = ausgabe + morsearray[morsekey][1] + " ";
	}

	return ausgabe;
    }

    // Hauptmethode
    public static void main(String[] args) {
	// Klassenobjekt um auf die Methode zugreifen zu können
	morsecode tue = new morsecode();
	// Scanner zum Einlesen der Eingabe
	Scanner scan = new Scanner(System.in);
	// Morsecode wird erstellt und ausgegeben
	System.out.println("Geben Sie den Text an, der in Morsecode"
		+ System.getProperty("line.separator")
		+ "umgewandelt werden soll:");
	System.out.println(tue.zuMorseUmwandeln(scan.nextLine()));

	scan.close();
    }

}
                

Lösung von: Sebastian Littel ()

// Kompiliert und getestet unter Linux 3.2.0

#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <string>
#include <map>

bool initMorse(std::map<char, std::string> &code);
bool toLowerSring(std::string &line);
bool generateMorse(std::map<char, std::string> &code, std::string &input, std::string &morse);

int main (void) {
    std::string morse = "";
    std::string input = "";
    std::map<char, std::string> code;

    if (false == initMorse(code)) {
        std::cout << "Error while initializing the code." << std::endl;
        exit(EXIT_FAILURE);
    }

    std::cout << "Please enter characters to be encoded: ";
    getline(std::cin, input);

    if (false == toLowerSring(input)) {
        std::cout << "Error while lowering the input string." << std::endl;
        exit(EXIT_FAILURE);
    }

    if (false == generateMorse(code, input, morse)) {
        std::cout << "Error while generating the morse code." << std::endl;
        exit(EXIT_FAILURE);
    }
    else {
        std::cout << "Morse coding: " << morse << std::endl;
    }

    exit(EXIT_SUCCESS);
}

bool initMorse(std::map<char, std::string> &code) {
    bool retCode = true;

    code.insert(std::pair<char, std::string>('a', ".-"));
    code.insert(std::pair<char, std::string>('b', "-..."));
    code.insert(std::pair<char, std::string>('c', "-.-."));
    code.insert(std::pair<char, std::string>('d', "-.."));
    code.insert(std::pair<char, std::string>('e', "."));
    code.insert(std::pair<char, std::string>('f', "..-."));
    code.insert(std::pair<char, std::string>('g', "--."));
    code.insert(std::pair<char, std::string>('h', "...."));
    code.insert(std::pair<char, std::string>('i', ".."));
    code.insert(std::pair<char, std::string>('j', ".---"));
    code.insert(std::pair<char, std::string>('k', "-.-"));
    code.insert(std::pair<char, std::string>('l', ".-.."));
    code.insert(std::pair<char, std::string>('m', "--"));
    code.insert(std::pair<char, std::string>('n', "-."));
    code.insert(std::pair<char, std::string>('o', "---"));
    code.insert(std::pair<char, std::string>('p', ".--."));
    code.insert(std::pair<char, std::string>('q', "--.-"));
    code.insert(std::pair<char, std::string>('r', ".-."));
    code.insert(std::pair<char, std::string>('s', "..."));
    code.insert(std::pair<char, std::string>('t', "-"));
    code.insert(std::pair<char, std::string>('u', "..-"));
    code.insert(std::pair<char, std::string>('v', "...-"));
    code.insert(std::pair<char, std::string>('w', ".--"));
    code.insert(std::pair<char, std::string>('x', "-..-"));
    code.insert(std::pair<char, std::string>('y', "-.--"));
    code.insert(std::pair<char, std::string>('z', "--.."));
    code.insert(std::pair<char, std::string>('0', "-----"));
    code.insert(std::pair<char, std::string>('1', ".----"));
    code.insert(std::pair<char, std::string>('2', "..---"));
    code.insert(std::pair<char, std::string>('3', "...--"));
    code.insert(std::pair<char, std::string>('4', "....-"));
    code.insert(std::pair<char, std::string>('5', "....."));
    code.insert(std::pair<char, std::string>('6', "-...."));
    code.insert(std::pair<char, std::string>('7', "--..."));
    code.insert(std::pair<char, std::string>('8', "---.."));
    code.insert(std::pair<char, std::string>('9', "----."));
    code.insert(std::pair<char, std::string>('.', ".-.-.-"));
    code.insert(std::pair<char, std::string>(',', "--..--"));
    code.insert(std::pair<char, std::string>(':', "---..."));
    code.insert(std::pair<char, std::string>(';', "-.-.-."));
    code.insert(std::pair<char, std::string>('?', "..--.."));
    code.insert(std::pair<char, std::string>('-', "-....-"));
    code.insert(std::pair<char, std::string>('+', ".-.-."));
    code.insert(std::pair<char, std::string>('@', ".--.-."));

    return retCode;
}

bool toLowerSring(std::string &line) {
    bool retCode = true;

    std::transform(line.begin(), line.end(), line.begin(), ::tolower);

    return retCode;
}

bool generateMorse(std::map<char, std::string> &code, std::string &input, std::string &morse) {
    bool retCode = true;

    for (int i = 0; i < input.size(); ++i) {
        if (input[i] == ' ') {
            morse.append("| ");
        }
        else {
            morse.append(code.find(input[i])->second);
            morse.append(" ");
        }
    }

    return retCode;
}

                

Lösung von: Matthias Sayler (Bosch)

/**
  *
  * Convert Input String to Morse sentence
  *
  * @version 1.0 from 30.06.2014
  * @Jared Gesser 
  */

import java.util.Scanner;
public class morse {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Was soll uebersetzt werden?");
    translate(sc.nextLine()); 
  }
  
  static void translate(String in) {
    String[] input = in.split("(?!^)");
    String[] output = new String[input.length];
    
    String[] vals = {".-  ","-...","-.-.","-.. ",".   ","..-.","--. ","....","..  ",".---","-.- ",".-..","--  ","-.  ","--- ",".--.","--.-",".-. ","... ","-   ","..- ","...-",".-- ","-..-","-.--","--..","-----",".----","..---","...--","....-",".....","-....","--...","---..","----.",".-.-.-","--..--","/"};
    String[] src  = {"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",".",","," "};
    
    for (int y = 0;y < input.length ;y++ ) {
      for (int x = 0;x <src.length ;x++ ) {
        if (src[x].equalsIgnoreCase(input[y])) {
          output[y] = vals[x];
        } // end of if
      } // end of for
    } // end of for
    
    System.out.println("Die Morse-Botschaft lautet:");
    for (int i = 0;i < output.length ;i++ ) {
      if (input[i].equals(" ") || input[i].equals(",") || input[i].equals(".")) {
        if (input[i].equals(" ")) {
          System.out.println();
          System.out.println(output[i]+"           [leer]");
          System.out.println();
        } // end of if
        if (input[i].equals(",")) {
          System.out.println(output[i]+"      ,");
        } // end of if
        if (input[i].equals(".")) {
          System.out.println(output[i]+"      .");
        } // end of if
      } else {
        System.out.println(output[i]+"        "+input[i].toUpperCase());
      } // end of if-else
    } // end of for
  }
}
                

Lösung von: Jared Gesser (Landrat-Gruber-Schule BSZ HBFI-T)

# Python 3.4.2

morsecode = {' ': '   ', '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': '????·', '.': '·?·?·?',',': '??··??',': ': '???···',';': '?·?·?·','?': '··??··','-': '?····?','_': '··??·?','(': '?·??·',')': '?·??·?',"'": '·????·','=': '?···?','+': '·?·?·','/': '?··?·','@': '·??·?·'}
morsetext = str()

rawtext = input('Please enter the text to be morse coded: ')
rawtextGross = rawtext.upper()

for i in rawtextGross:
    morsetext = morsetext + morsecode.get(i) + ' '

print(morsetext)
                

Lösung von: Hilli Hilli ()

using System;
using System.Collections.Generic;
using System.Text;

namespace Morse_Code {
	class Program {
		static void Main() {
			Dictionary<char, string> MorseCode = new Dictionary<char, string>() {
				{'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', "----."}, {'à', ".--.-"}, 
				{'å', ".--.-"}, {'ä', ".-.-"}, {'è', ".-..-"}, {'é', "..-.."},
				{'ö', "---."}, {'ü', "..--"}, {'ß', "...--.."}, {'ñ', "--.--"},
				{'.', ".-.-.-"}, {',', "--..--"}, {':', "---..."}, {';', "-.-.-."},
				{'?', "..--.."}, {'-', "-....-"}, {'_', "..--.-"}, {'(', "-.--."},
				{')', "-.--.-"}, {'\'', ".----."}, {'=', "-...-"}, {'+', ".-.-."},
				{'/', "-..-."}, {'@', ".--.-."}, {' ', "   "}
			};
			StringBuilder Ausgabe = new StringBuilder();
			char[] Eingabe;

			Console.Write("Eingabe> ");
			Eingabe = Console.ReadLine().ToLower().ToCharArray();

			for (int i = 0; i < Eingabe.Length; i++) {
				if (i % 20 == 0)
					Ausgabe.Append('\n');

				try {
					Ausgabe
						.Append(MorseCode[Eingabe[i]])
						.Append(' ');
				}
				catch (KeyNotFoundException) { }
			}
			Console.WriteLine("\nMorse:" + Ausgabe);

			Console.ReadKey(true);
		}
	}
}
                

Lösung von: Marcel Kapma ()

function txt2morse(str) {
   var morse = "",
       i = 0;
       
       // Unicode [32-90] in Morsecode
       var codes = ["  ", "-·-·--", "·-··-·", /*#*/ , "···-··-", /*%*/, "·-···", 
         "·----·", "-·--·", "-·--·-", /***/, "·-·-·", "--··--", "-····-", 
         "·-·-·-", "-··-·", "-----", "·----", "··---", "···--", "····-", 
         "·····", "-····", "--···", "---··", "----·", "---···", "-·-·-·", /*<*/, 
         "-···-", /*>*/, "··--··", "·--·-·", "·-", "-···", "-·-·", "-··", "·", 
         "··-·", "--·", "····", "··", "·---", "-·-", "-·--", "--", "-·", "---", 
         "·--·", "--·-", "·-·", "···", "-", "··-", "···-", "·--", "-··-", 
         "-·--", "--··"];
      
      str = str.trim();
      str = str.replace(/Ä|ä/g, "A~A");  // ·- ~ ·- etc.
      str = str.replace(/Ö|ö/g, "O~E");  
      str = str.replace(/Ü|ü/g, "U~T");  
      str = str.replace(/ß/g, "S~Z");    
      str = str.toUpperCase();
      
      while (i < str.length) {
         morse += codes[str.charCodeAt(i)-32];
         if (str.charAt(i+1) == "~") i++; else morse += " ";
         i++;
      }
         
      return morse;
}

console.log(txt2morse("sos"));


                

Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)

#morsecode
l_dict = {"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":"--.."," ":" "}

def check(letter):
    if letter in l_dict:
        return l_dict[letter]

def parse(nachricht):
    
    nach_morse = ""
    for i in nachricht:
        morse = check(i.upper())
        nach_morse += morse + " "
    print(nach_morse)
    
def main():
    nachricht = raw_input("Nachricht: ")
    parse(nachricht)

if __name__ == "__main__":
    main()
                

Lösung von: Name nicht veröffentlicht

REPORT Morsecode.

PARAMETERS lv_text TYPE string.

DATA lv_zahl(3) TYPE c.
DATA lv_wert TYPE c.
DATA lv_ausg TYPE string.

lv_zahl = strlen( lv_text ).

WRITE:/ 'Die Übersetzung von ', lv_text, ' in Morsecode lautet:'.
new-line.

DO lv_zahl TIMES.
    lv_wert = lv_text+0.

    IF lv_wert = 'A'.
       lv_ausg = '·-  '.
    ELSEIF lv_wert = 'B'.
       lv_ausg = '-··· '.
    ELSEIF lv_wert = 'C'.
       lv_ausg = '-·-· '.
    ELSEIF lv_wert = 'D'.
       lv_ausg = '-·· '.
    ELSEIF lv_wert = 'E'.
       lv_ausg = '· '.
    ELSEIF lv_wert = 'F'.
       lv_ausg = '··-· '.
    ELSEIF lv_wert = 'G'.
       lv_ausg = '--· '.
    ELSEIF lv_wert = 'H'.
       lv_ausg = '····'.
    ELSEIF lv_wert = 'I'.
       lv_ausg = '·-'.
    ELSEIF lv_wert = 'J'.
       lv_ausg = '·--- '.
    ELSEIF lv_wert = 'K'.
       lv_ausg = '-·- '.
    ELSEIF lv_wert = 'L'.
       lv_ausg = '·-·· '.
    ELSEIF lv_wert = 'M'.
       lv_ausg = '-- '.
    ELSEIF lv_wert = 'N'.
       lv_ausg = '-· '.
    ELSEIF lv_wert = 'O'.
       lv_ausg = '--- '.
    ELSEIF lv_wert = 'P'.
       lv_ausg = '·--· '.
    ELSEIF lv_wert = 'Q'.
       lv_ausg = '--·- '.
    ELSEIF lv_wert = 'R'.
       lv_ausg = '·-· '.
    ELSEIF lv_wert = 'S'.
       lv_ausg = '··· '.
    ELSEIF lv_wert = 'T'.
       lv_ausg = '- '.
    ELSEIF lv_wert = 'U'.
       lv_ausg = '··- '.
    ELSEIF lv_wert = 'V'.
       lv_ausg = '···- '.
    ELSEIF lv_wert = 'W'.
       lv_ausg = '·-- '.
    ELSEIF lv_wert = 'X'.
       lv_ausg = '-··- '.
    ELSEIF lv_wert = 'Y'.
       lv_ausg = '-·-- '.
    ELSEIF lv_wert = 'Z'.
       lv_ausg = '--·· '.

    ELSEIF lv_wert = '1'.
       lv_ausg = '.---- '.
    ELSEIF lv_wert = '2'.
       lv_ausg = '··--- '.
    ELSEIF lv_wert = '3'.
       lv_ausg = '···-- '.
    ELSEIF lv_wert = '4'.
       lv_ausg = '····- '.
    ELSEIF lv_wert = '5'.
       lv_ausg = '····· '.
    ELSEIF lv_wert = '6'.
       lv_ausg = '-···· '.
    ELSEIF lv_wert = '7'.
       lv_ausg = '--··· '.
    ELSEIF lv_wert = '8'.
       lv_ausg = '---·· '.
    ELSEIF lv_wert = '9'.
       lv_ausg = '----· '.
    ELSEIF lv_wert = '0'.
       lv_ausg = '----- '.

    ELSEIF lv_wert = 'À'.
       lv_ausg = '·--·-'.
    ELSEIF lv_wert = 'Å'.
       lv_ausg = '·--·-'.
    ELSEIF lv_wert = 'Ä'.
       lv_ausg = '·-·-'.
    ELSEIF lv_wert = 'È'.
       lv_ausg = '·-··-'.
    ELSEIF lv_wert = 'É'.
       lv_ausg = '··-··'.
    ELSEIF lv_wert = 'Ö'.
       lv_ausg = '---·'.
    ELSEIF lv_wert = 'Ü'.
       lv_ausg = '··--'.
    ELSEIF lv_wert = 'ß'.
       lv_ausg = '···--··'.
    ELSEIF lv_wert = 'Ñ'.
       lv_ausg = '--·--'.
    ELSEIF lv_wert = '.'.
       lv_ausg = '·-·-·'.
    ELSEIF lv_wert = ','.
       lv_ausg = '--··--'.
    ELSEIF lv_wert = ':'.
       lv_ausg = '---···'.
    ELSEIF lv_wert = ';'.
       lv_ausg = '-·-·-·'.
    ELSEIF lv_wert = '?'.
       lv_ausg = '··--··'.
    ELSEIF lv_wert = '-'.
       lv_ausg = '-····-'.
    ELSEIF lv_wert = '_'.
       lv_ausg = '··--·-'.
    ELSEIF lv_wert = '('.
       lv_ausg = '-·--·'.
    ELSEIF lv_wert = ')'.
       lv_ausg = '-·--·-'.
    ELSEIF lv_wert = '='.
       lv_ausg = '-···-'.
    ELSEIF lv_wert = '+'.
       lv_ausg = '·-·-·'.
    ELSEIF lv_wert = '/'.
       lv_ausg = '-··-·'.
    ELSEIF lv_wert = '@'.
       lv_ausg = '-··-·'.


    ELSEIF lv_wert = ' '.
       lv_ausg = '   '.


    ENDIF.

    WRITE lv_ausg.

    SHIFT lv_text LEFT BY 1 places.


ENDDO.
                

Lösung von: Name nicht veröffentlicht

Morsealphabet = ["·?", "?···", "?·?·", "?··", "·", "··?·", "??·", "····", "··", "·???", "?·?", "·?··", "??",
                 "?·", "???", "·??·", "??·?", "·?·", "···", "?", "··?", "···?", "·??", "?··?", "?·??", "??··"]
morse = ""
text = input("Bitte Text eingeben: ")

for buchstabe in text:
    if buchstabe == " ":
        morse += "  "
    else:
        morse += Morsealphabet[ord(buchstabe.upper()) - 65] + " "

print(morse)
                

Lösung von: Peter Pan (Home Office)

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 1
Schwierigkeit: Leicht
Webcode: 0bgw-abqq
Autor: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen