A-level 计算机科学/AQA/试卷 1/程序框架/AS2018
这是针对 AQA AS 计算机科学规范的。
在这里可以提出关于一些问题可能是什么以及如何解决它们的建议。
请保持尊重,不要破坏或篡改页面,因为这会影响学生备考!
修改程序,以便用户可以将传输(从空格和等号的形式)读写到二进制格式(以减少存储空间)。
C#
Delphi/Pascal
Java
Python
# These functions need to be added to relavent subroutines if support for a binary file is required:
# BinaryEncode result passed as parameter to BinaryWrite with filename, called from SendMorseCode (pass MorseCodeString to BinaryEncode)
# BinaryRead result (parameter is file name) passed as parameter to BinaryDecode, and the return is to be used as variable Transmission in GetTransmission()
# Python binary file handling reads / writes in bytes. Therefore, for optimum usage, we need to be making full use of each byte. Letting a space be a 0 and an equals sign be 1, each 8 characters from the currently supported text file become 1 byte. Leftmost character = first value in each byte, 8n th = last byte of array
def BinaryEncode(Message):
Bytes = []
Current = 128
Count = 0
for Character in Message:
if Current == 0.5:
Bytes.append(int(Count))
Count = 0
Current = 128
if Character == '=':
Count += Current
Current = Current / 2
if Count != 0:
Bytes.append(int(Count))
return bytes(Bytes) # base10 -> base2 value
def BinaryWrite(Bytes, FileName):
FileHandle = open(FileName, 'wb')
FileHandle.write(Bytes)
FileHandle.flush()
FileHandle.close()
def BinaryRead(FileName):
FileHandle = open(FileName, 'rb')
ByteValues = list(FileHandle.read()) # base2 -> base10 value
FileHandle.close()
return ByteValues
def BinaryDecode(Bytes):
Message = str()
for Byte in Bytes:
for BitValue in [128, 64, 32, 16, 8, 4, 2, 1]:
if Byte >= BitValue:
Byte -= BitValue
Message += '='
else:
Message += ' '
return Message
# Example usage (using message from preliminary material
Bin = (BinaryEncode("=== = = === === = = === "))
BinaryWrite(Bin, 'binfile')
print(BinaryDecode(BinaryRead('binfile')))
VB.NET
此问题涉及GetTransmission和ReceiveMorseCode子程序。该问题要求创建GetKey和DecryptTransmission子程序。
程序框架需要进行调整,以便能够接收和解密使用替换密码加密的消息。解密方法是将解密密钥应用于消息。
在替换密码中,每个字符都被替换成另一个字符。例如,每个字母 A 都可以替换成数字 7。
解密密钥将存储在一个文本文件中,包含 36 个字符。前 26 个字符将代表字母 A - Z,接下来的 10 个字符将代表数字 0 - 9。
需要创建一个新的 GetKey 子程序,它将从用户指定的文件中读取并返回密钥。如果未指定密钥,则该子程序应返回密钥:ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789。此密钥应解释为每个字符都代表它本身。
需要创建一个新的 DecryptTransmission 子程序,它将解密密钥应用于传输。它将由 ReceiveMorseCode 中的新行调用,插入到print(PlainText)之前。
PlainText = DecryptTransmission(PlainText)。
C#
Delphi/Pascal
Java
Python
def ReceiveMorseCode(Dash, Letter, Dot):
PlainText = EMPTYSTRING
MorseCodeString = EMPTYSTRING
Transmission = GetTransmission()
LastChar = len(Transmission) - 1
i = 0
while i < LastChar:
i, CodedLetter = GetNextLetter(i, Transmission)
MorseCodeString = MorseCodeString + SPACE + CodedLetter
PlainTextLetter = Decode(CodedLetter, Dash, Letter, Dot)
PlainText = PlainText + PlainTextLetter
print(MorseCodeString)
PlainText = DecryptTransmission(PlainText)
print(PlainText)
def GetKey():
theline = ''
with open('keykey.txt', 'r') as decryptionkey:
for line in decryptionkey:
theline = line
return theline
def DecryptTransmission(gibberish):
keys = GetKey()
#print(keys)
keylst = []
for i in keys:
keylst.append(i)
actualword = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
decryptedmessage = ''
for lettertodecrypt in gibberish:
if lettertodecrypt in keys:
decryptedmessage += actualword[keylst.index(lettertodecrypt)]
elif lettertodecrypt == ' ':
decryptedmessage += ' '
else:
print('Invalid')
return decryptedmessage
VB.NET
程序当前在输入错误选项时只是再次打印菜单;添加验证,以便程序在输入无效选项时打印一条消息。
C#
switch (MenuOption)
{
case "R":
ReceiveMorseCode(Dash, Letter, Dot);
break;
case "S":
SendMorseCode(MorseCode);
break;
case "X":
ProgramEnd = true;
break;
default:
Console.WriteLine("You have made an invalid selection. Try again");
break;
}
Delphi/Pascal
Procedure SendReceiveMessages();
const
Dash: array[0..26] of Integer = (20,23,0,0,24,1,0,17,0,21,0,25,0,15,11,0,0,0,0,22,13,0,0,10,0,0,0);
Dot : array[0..26] of Integer = (5,18,0,0,2,9,0,26,0,19,0,3,0,7,4,0,0,0,12,8,14,6,0,16,0,0,0);
Letter : array[0..26] of Char= (' ','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');
MorseCode : array[0..26] of String= (' ','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..');
var
ProgramEnd : Boolean;
MenuOption : String;
begin
ProgramEnd := False;
while not(ProgramEnd) do
begin
DisplayMenu();
MenuOption := GetMenuOption();
if (MenuOption = 'R') or (MenuOption ='r') then
ReceiveMorseCode(Dash, Letter, Dot)
else if (MenuOption = 'S') or (MenuOption='s') then
SendMorseCode(MorseCode)
else if (MenuOption = 'X') or (menuOption='x') then
ProgramEnd := True
else
writeln('you did not enter a valid option.');
readln;
end;
end
Java
static void sendReceiveMessages() throws IOException {
int[] dash = { 20, 23, 0, 0, 24, 1, 0, 17, 0, 21, 0, 25, 0, 15, 11, 0, 0, 0, 0, 22, 13, 0, 0, 10, 0, 0, 0 };
int[] dot = { 5, 18, 0, 0, 2, 9, 0, 26, 0, 19, 0, 3, 0, 7, 4, 0, 0, 0, 12, 8, 14, 6, 0, 16, 0, 0, 0 };
char[] letter = { ' ', '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' };
String[] morseCode = { " ", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-",
".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--",
"--.." };
boolean programEnd = false;
while (!programEnd) {
displayMenu();
String menuOption = scan.next();
if (menuOption.equalsIgnoreCase("r")) {
receiveMorseCode(dash, letter, dot);
} else if (menuOption.equalsIgnoreCase("s")) {
sendMorseCode(morseCode);
} else if (menuOption.equalsIgnoreCase("x")) {
programEnd = true;
}else {
System.out.println("That was an Incorrect Input");
}
}
}
Python
def GetMenuOption():
MenuOption = EMPTYSTRING
Correct = False
while len(MenuOption) != 1:
MenuOption = input("Enter your choice: ")
if MenuOption == 'R' or MenuOption == 'S' or MenuOption == 'X':
Correct = True
else:
{{CPTAnswerTab|C#}}
MenuOption = input("Invalid choice. Re-Enter your choice: ")
return MenuOption
## Change from lower to upper case with ascii incase they lead you up to it or tell you to use ascii instead of .upper()
def GetMenuOption():
MenuOption = EMPTYSTRING
while len(MenuOption) != 1:
MenuOption = raw_input("Enter your choice: ")
Ascii = ord(MenuOption)
if Ascii>=97:
Ascii=Ascii-32
MenuOption=chr(Ascii)
return MenuOption
VB.NET
更新接收信号以允许直接输入而不是 txt 文件。
C#
private static string GetTransmission()
{
string choice = EMPTYSTRING;//declares to empty
Console.WriteLine ("Would you like to load a file (Y/N)");//outputs the line
choice = Console.ReadLine().ToUpper();//assigns the value
string Transmission;//declares
if (choice == "Y")
{
string FileName = EMPTYSTRING; //declare
Console.Write("Enter file name: ");//outputty
FileName = (Console.ReadLine() + ".txt");//assigns
try//error handling
{
Transmission = File.ReadAllText(FileName);//assings varaible to text from the file in bin
Transmission = StripLeadingSpaces(Transmission);//removes spaces at the start of the transmission
if (Transmission.Length > 0)//chekcs length
{
Transmission = StripTrailingSpaces(Transmission);//strips spaces from the end of the text
Transmission = Transmission + EOL; //adds the global to it
}
}
catch
{
ReportError("No transmission found"); //catches if the try errors calling sub
//give instructions
Console.WriteLine("Please enter a valid text file name that is in the bin/debug");
Transmission = EMPTYSTRING;//assigns it to empty
}
}
else
{
Console.WriteLine("Please enter your transmission");//outputs
Transmission = Console.ReadLine();//assigns
Transmission = StripLeadingSpaces(Transmission);//strips spaces at the start
if (Transmission.Length > 0)//chekcs length
{
Transmission = StripTrailingSpaces(Transmission);//strips spaces from the end of the text
Transmission = Transmission + EOL; //adds the global to it
}
}
return Transmission;//returns transmission
}
THIS REQUIRES AN INPUT OF TRANSMISSION RATHER THAN DIRECT MORSE
Delphi/Pascal
Function GetTransmissionFromFile() : String;
var
FileName : String;
FileHandle : Textfile;
Transmission : String;
begin
write('Enter file name: ');
readln(FileName);
try
assign(FileHandle,FileName);
reset(FileHandle);
readln(FileHandle, Transmission);
close(FileHandle);
Transmission := StripLeadingSpaces(Transmission);
if length(Transmission) > 0 then
begin
Transmission := StripTrailingSpaces(Transmission);
Transmission := Transmission + EOL;
end;
except
on E: exception do
begin
ReportError('No transmission found');
Transmission := EMPTYSTRING;
end;
end ;
GetTransmissionFromFile := Transmission;
end;
Function GetTransmissionFromInput() : String;
var
transmission : String;
begin
writeln('please enter your transmission (using = to signify on and a space to represent off) ');
readln(transmission);
Transmission :=StripLeadingSpaces(Transmission);
if length(Transmission) > 0 then
begin
Transmission := StripTrailingSpaces(Transmission);
Transmission := Transmission + EOL;
end;
GetTransmissionFromInput := Transmission;
end;
Function GetAnyTransmission() : string;
var
choice: string;
valid: integer;
begin
repeat
begin
writeln('Do you want to receive transmission from a file?(Y/N) ');
readln (choice);
if (Choice = 'Y') or (Choice = 'y') or (Choice = 'yes') or (Choice= 'YES') or (Choice= 'Yes') then
begin
valid := 1;
GetAnyTransmission := GetTransmissionFromFile();
end
else if (Choice ='N') or (Choice = 'n') or (Choice = 'no') or (Choice= 'NO') or (Choice ='No') then
begin
valid := 1;
GetAnyTransmission := GetTransmissionFromInput();
end
else
begin
valid := 0;
writeln('You have not entered a valid response');
end;
end;
until Valid = 1;
end;
Java
Python
def GetTransmission():
choice = input("Would you like to load a file? (Y/N): ")
if choice == "Y":
FileName = input("Enter file name: ")
try:
FileHandle = open(FileName, 'r')
Transmission = FileHandle.readline()
FileHandle.close()
Transmission = StripLeadingSpaces(Transmission)
if len(Transmission) > 0:
Transmission = StripTrailingSpaces(Transmission)
Transmission = Transmission + EOL
except:
ReportError("No transmission found")
Transmission = EMPTYSTRING
else:
Transmission = input("Enter your transmission String: ")
Transmission = StripLeadingSpaces(Transmission)
if len(Transmission) > 0:
Transmission = StripTrailingSpaces(Transmission)
Transmission = Transmission + EOL
return Transmission
VB.NET
Function GetTransmission() As String
Dim Filename As String
Dim Transmission As String
Dim choice As String
Console.WriteLine("Do you wish to load a file?")
choice = Console.ReadLine
If choice = "yes " Then
Console.Write("Enter file name: ")
Try
Filename = Console.ReadLine()
Dim Reader As New StreamReader(Filename)
Transmission = Reader.ReadLine
Reader.Close()
Transmission = StripLeadingSpaces(Transmission)
If Transmission.Length() > 0 Then
Transmission = StripTrailingSpaces(Transmission)
Transmission = Transmission + EOL
End If
Catch
ReportError("No transmission found")
Transmission = EMPTYSTRING
End Try
Else
Console.WriteLine("please enter the morse code string")
Transmission = Console.ReadLine
Transmission = StripLeadingSpaces(Transmission)
If Transmission.Length() > 0 Then
Transmission = StripTrailingSpaces(Transmission)
Transmission = Transmission + EOL
End If
End If
Return Transmission
End Function
- 将生成的摩尔斯电码转换为传输信号。
- 将传输信号写入 txt 文件。
C#
// Add SaveToFile(MorseCodeString) to last line of the SendMorseCode() subroutine, and also define the following subroutines:
private static void SaveToFile(string MorseCodeString) // ADDED - SAVE TO FILE
{
Console.WriteLine("Would You like to save the message to a file (Y/N)?");
string SaveChoice = Console.ReadLine(); // Check whether user wants to save to file
if (SaveChoice[0] == 'y' || SaveChoice[0] == 'Y') // [0] to only account for first character of input (both cases checked)
{
try
{
Console.WriteLine("Enter the name of the file to save the message to: ");
string FileName = Console.ReadLine(); // User input file name
if (!FileName.Contains(".txt")) // If it doesn't contain '.txt' then add the ".txt" to FileName
{
FileName += ".txt"; // Append .txt if not present
}
StreamWriter FileSaver = new StreamWriter(FileName); // Open file in write mode (new StreamWriter)
FileSaver.Write(MorseCodeString); // Write the MorseCodeString to the File chosen
FileSaver.Close();
}
catch
{
ReportError("Error when writing to file."); // Error handling message
}
Console.WriteLine("File successfully written");
}
}
Delphi/Pascal
Java
static void sendMorseCode(String[] morseCode) throws IOException {
Console.write("Enter your message (uppercase letters and spaces only): ");
String plainText = Console.readLine();
plainText=plainText.toUpperCase();
int plainTextLength = plainText.length();
String morseCodeString = EMPTYSTRING;
int index;
for (int i = 0; i < plainTextLength; i++) {
char plainTextLetter = plainText.charAt(i);
if (plainTextLetter == SPACE) {
index = 0;
} else {
index = (int) plainTextLetter - (int) 'A' + 1;
}
String codedLetter = morseCode[index];
morseCodeString = morseCodeString + codedLetter + SPACE;
}
Console.writeLine(morseCodeString);
System.out.println("Do you want to save you message \n 1:Y \n 2:N");
String choice = scan.next();
switch(choice) {
case "Y":
filewriter(morseCodeString);
break;
case "N":
break;
default:
System.out.println("That was not an option /n Your data will be stored");
filewriter(morseCodeString);
break;
}
}
public static void filewriter(String sendMorseCode) throws IOException {
System.out.println("Enter the name of the file");
String filename = scan.next();
FileWriter fw = new FileWriter(filename);
PrintWriter end = new PrintWriter(fw);
end.print(sendMorseCode);
end.close();
fw.close();
}
Python
#SBaker May 18 4. Save a text file when sending Morse Code
#we need to format MorseCodeString into the output format
outputString = ''
for letter in MorseCodeString:
if letter == '.':
outputString = outputString + "= "
elif letter == '-':
outputString = outputString + "=== "
elif letter == ' ':
outputString = outputString + " "
FileName = input("Enter file name: ")
try:
FileHandle = open(FileName, 'w')
FileHandle.write(outputString)
FileHandle.close()
except:
ReportError("No file found")
VB.NET
Sub SendMorseCode(ByVal MorseCode() As String)
Dim PlainText As String
Dim PlainTextLength As Integer
Dim MorseCodeString As String
Dim PlainTextLetter As Char
Dim CodedLetter As String
Dim Index As Integer
Console.Write("Enter your message (letters and spaces only): ")
PlainText = Console.ReadLine()
PlainText = PlainText.ToUpper()
PlainTextLength = PlainText.Length()
MorseCodeString = EMPTYSTRING
For i = 0 To PlainTextLength - 1
PlainTextLetter = PlainText(i)
If PlainTextLetter = SPACE Then
Index = 0
Else
Index = Asc(PlainTextLetter) - Asc("A") + 1
End If
CodedLetter = MorseCode(Index)
MorseCodeString = MorseCodeString + CodedLetter + SPACE
Next
Console.WriteLine(MorseCodeString)
Console.WriteLine("Would you like to save this to a text file?")
Dim save As String = Console.ReadLine()
If save = "Y" Or save = "y" Then
Dim fileTitle As String
Console.WriteLine("What would you like to call the file?")
fileTitle = Console.ReadLine()
Dim fileLoc As String
fileLoc = "H:\Documents\2018 June\VB\" + fileTitle + ".txt"
Dim fs As New FileStream(fileLoc, FileMode.CreateNew, FileAccess.Write)
Dim sw As New StreamWriter(fs)
sw.WriteLine(MorseCodeString)
sw.Flush()
Else
Console.WriteLine("Okay.")
Console.ReadLine()
End If
End Sub
- 将生成的摩尔斯电码转换为传输信号。
- 将传输信号写入 txt 文件。
C#
// Add EncodeMorseCode(MorseCodeString) to last line of the SendMorseCode() subroutine, and also define the following subroutines:
private static void EncodeMorseCode(string MorseCode) // Function to convert MorseCodeString to the '=' and (Space) format in Preliminary Material
{
Console.WriteLine("Would You like to save the message to a file (Y/N)?");
string ShouldSave = Console.ReadLine(); // Check whether user wants to save to file
if (ShouldSave[0] == 'y' || ShouldSave[0] == 'Y') // [0] to only account for first character of input (both cases checked)
{
try
{
Console.WriteLine("Enter the name of the file to save the message to: ");
string FileName = Console.ReadLine(); // User input file name
if (!FileName.Contains(".txt")) // If it doesn't contain '.txt' then add the ".txt" to FileName
{
FileName += ".txt"; // Append .txt if not present
}
StreamWriter CodedFileSaver = new StreamWriter(FileName); // Open file in write mode (new StreamWriter)
// Use the built-in .Replace(old, new) method to swap out the relevant characters in C#.
string CodedOutput = MorseCode.Replace("-", "=== ").Replace(".", "= ").Replace(" ", " ").Replace(" ", " ");
// This now effectively formats the MorseCodeString message to the '=' and ' ' format
CodedFileSaver.Write(CodedOutput);
CodedFileSaver.Close();
}
catch
{
ReportError("Error when writing to file."); // Error handling
}
Console.WriteLine("Coded File successfully written");
}
}
// S Wood - Teach
Delphi/Pascal
Procedure SaveTransmission(Transmission : string);
var
FileHandle : TextFile;
begin
AssignFile(FileHandle, 'Message.txt');
try
rewrite (FileHandle);
writeln (FileHandle, Transmission);
CloseFile (FileHandle);
except
on E: exception do
writeln ('Exception: ', E.Message);
end;
end;
Procedure SendMorseCode(MorseCode : Array of String);
var
PlainText, MorseCodeString, CodedLetter, TransmissionString : String;
PlainTextLength, i, Index, k : Integer;
PlainTextLetter : Char;
begin
write('Enter your message (uppercase letters and spaces only): ');
readln(PlainText);
PlainTextLength := length(PlainText);
MorseCodeString := EMPTYSTRING;
TransmissionString := EMPTYSTRING;
for i := 1 to PlainTextLength do
begin
PlainTextLetter := PlainText[i];
if PlainTextLetter = SPACE then
Index := 0
else
Index := ord(PlainTextLetter) - ord('A') + 1;
CodedLetter := MorseCode[Index];
for k := 1 to length(CodedLetter) do
begin
case CodedLetter[k] of
' ': TransmissionString += ' ';
'.': TransmissionString += '=';
'-': TransmissionString += '==='
end;
TransmissionString += ' ';
end;
MorseCodeString := MorseCodeString + CodedLetter + SPACE;
if i <> PlainTextLength then
TransmissionString += ' ';
end;
writeln(MorseCodeString);
SaveTransmission(TransmissionString);
writeln ('Message encoded and saved in Message.txt');
end;
Java
for (int i = 0; i < morseCodeString.length(); i++) {
char c = morseCodeString.charAt(i);
if (c == '-') {
morseCodeTransmission = morseCodeTransmission + " ===";
}
if (c == '.') {
morseCodeTransmission = morseCodeTransmission + " =";
}
if (c == ' ') {
morseCodeTransmission = morseCodeTransmission + " ";
}
}
System.out.println("Name the file you would like to save this too");
String fileName = Console.readLine();
if (!fileName.contains(".txt")) {
fileName = fileName + ".txt";
}
try {
BufferedWriter fileHandle = new BufferedWriter(new FileWriter(fileName));
fileHandle.write(morseCodeTransmission);
fileHandle.close();
} catch (IOException e) {
}
Python
# Add SaveToFile(MorseCodeString) to last line of the SendMorseCode() subroutine, and also define the following subroutines:
def SaveToFile(MorseCodeString): # ADDED - SAVE TO FILE
ShouldSave = input("Would You like to save the message to a file (Y/N)?") # Check whether user wants to save to file
if ShouldSave[0].lower() == 'y': # .lower to make casing irrelevant, [0] to only account for first character (e.g. yes will also be accepted)
try:
FileName = input("Enter the name of the file to save the message to: ") # User input file name
if ' '+FileName[-4].lower() != '.txt': # Check if file extension is .txt. The ' ' at start is 4 spaces in order to prevent error from index not existing (if file name was under 4 characters)
FileName += '.txt' # Append .txt if not present
FileHandle = open(FileName, 'w') # Open file in write mode
FileHandle.write(EncodeMorseCode(MorseCodeString)) # Write the encoded message to file
FileHandle.close()
except:
ReportError("Error when writing to file.") # Error handling
def EncodeMorseCode(MorseCode): # Function to convert morse code to format saved in file
Output = MorseCode.replace('-', '=== ').replace('.', '= ').replace(' ', ' ').replace(' ', ' ') # Format message to required format
return Output # Return message to be saved to file
VB.NET
Sub SendMorseCode(ByVal MorseCode() As String)
Dim PlainText As String
Dim PlainTextLength As Integer
Dim MorseCodeString As String
Dim PlainTextLetter As Char
Dim CodedLetter As String
Dim Index As Integer
Dim save As Integer
Dim file As StreamWriter
Dim file2 As String
Dim morsecodesymbol As String
Dim morsecodesymbolR As String
Dim morsecodemessage As String
Console.Write("Enter your message (uppercase letters and spaces only): ")
PlainText = Console.ReadLine()
PlainTextLength = PlainText.Length()
MorseCodeString = EMPTYSTRING
For i = 0 To PlainTextLength - 1
PlainTextLetter = PlainText(i)
If PlainTextLetter = SPACE Then
Index = 0
Else
If Asc(PlainTextLetter) < 65 Then
Index = Asc(PlainTextLetter) - 21
Else
Index = Asc(PlainTextLetter) - Asc("A") + 1
End If
End If
CodedLetter = MorseCode(Index)
MorseCodeString = MorseCodeString + CodedLetter + SPACE + SPACE + SPACE
Next
Console.WriteLine(MorseCodeString)
Console.WriteLine("would you like to save your message in a document? If so then please press 1 if not press 2")
Try
save = Console.ReadLine
Catch ex As Exception
Console.WriteLine("you have messed up the saving program, please do as asked")
End Try
If save = 1 Then
Console.WriteLine("your file will be saved please choose a name")
file2 = Console.ReadLine & ".txt"
For i = 0 To MorseCodeString.Length - 1
morsecodesymbol = MorseCodeString(i)
If morsecodesymbol = "-" Then
morsecodesymbolR = "==="
ElseIf morsecodesymbol = "." Then
morsecodesymbolR = "="
ElseIf morsecodesymbol = SPACE Then
morsecodesymbolR = " "
ElseIf morsecodesymbol = SPACE And morsecodesymbol = SPACE Then
morsecodesymbolR = " "
End If
morsecodemessage = morsecodemessage & " " & morsecodesymbolR
Next
File = New StreamWriter(file2)
File.Write(morsecodemessage)
File.Close()
End If
允许用户将数字和标点符号(其中有摩尔斯电码)转换为摩尔斯电码。
C#
Delphi/Pascal
Java
Python
def SendReceiveMessages(): # All lists here have been modified to support numbers & some punctuation ( .,?! ) by adding indexes 27 onwards. This has been modified so that sending & receiving (if only sending required, only the MorseCode list requires changing) works.
Dash = [20,23,0,45,24,1,0,17,31,21,28,25,0,15,11,42,0,0,46,22,13,48,30,10,0,0,44,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,27,0,38,40,37,0,29]
Dot = [5,18,33,0,2,9,0,26,32,19,0,3,0,7,4,43,0,0,12,8,14,6,0,16,0,0,34,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,36,35,0,0,46,39,47]
Letter = [' ','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', '.', ',', '?', '!']
MorseCode = [' ','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..', '-----', '.----', '..---', '...--', '....-', '.....', '-....', '--...', '---..', '----.', '.-.-.-', '--..--', '..--..', '-.-.--']
ProgramEnd = False
while not ProgramEnd:
DisplayMenu()
MenuOption = GetMenuOption()
if MenuOption == 'R':
ReceiveMorseCode(Dash, Letter, Dot)
elif MenuOption == 'S':
SendMorseCode(MorseCode)
elif MenuOption == 'X':
ProgramEnd = True
def SendMorseCode(MorseCode):
PlainText = input("Enter your message (uppercase letters and spaces only): ")
PlainTextLength = len(PlainText)
MorseCodeString = EMPTYSTRING
for i in range(PlainTextLength):
PlainTextLetter = PlainText[i]
if PlainTextLetter == SPACE:
Index = 0
elif PlainTextLetter.isalpha(): # Character in position is a letter
Index = ord(PlainTextLetter.upper()) - ord('A') + 1
elif PlainTextLetter.isnumeric(): # Character in position is a number
# 0 needs to be at index 27, so subtract unicode value of 0 and add 27 to get index of all numbers
Index = ord(PlainTextLetter) - ord('0') + 27
else: # Is not a number / letter / space, assume it is a symbol. If statements for all supported symbols, setting index to position in MorseCode list
if PlainTextLetter == '.':
Index = 37
elif PlainTextLetter == ',':
Index = 38
elif PlainTextLetter == '?':
Index = 39
elif PlainTextLetter == '!':
Index = 40
else: # Unsupported character, replace with space (could also output error here if needed)
Index = 0
CodedLetter = MorseCode[Index]
MorseCodeString = MorseCodeString + CodedLetter + SPACE
print(MorseCodeString)
VB.NET
Sub SendReceiveMessages()
Dim Dash = {20, 23, 0, 0, 24, 1, 0, 17, 31, 21, 28, 25, 0, 15, 11, 37, 45, 0, 40, 22, 13, 341, 30, 10, 0, 0, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 46, 0, 0, 0, 0, 0, 0, 0}
Dim Letter = {" ", "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", "OT", "ö", "/", "Ä", "ü", "+", "üe", "ZT", "Á", ",", "@", ".", "?"}
Dim Dot = {5, 18, 33, 0, 2, 9, 0, 26, 32, 19, 0, 3, 0, 7, 4, 38, 0, 0, 12, 8, 14, 6, 0, 16, 39, 0, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 42, 43, 48, 49, 0, 47}
Dim MorseCode = {" ", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--....", "---...", "----..", "-----.", "----", "---.", "-··-·", ".-.-", "..--", ".-.-.", "..--.", "--..-", ".--.-", "--..--", ".--.-.", ".-.-..", "..--.."}
- Symbols work in progress numbers work!
目前小写字符会使程序崩溃,添加功能以翻译小写字母并正确翻译数字/符号
C#
Delphi/Pascal
Java
// Does not have numbers or symbols. Any other instances in the code where it does not allow lower case use the code equalsIgnoreCase(
// The code below shows it working in the menu of the Program
static void sendReceiveMessages() throws IOException {
int[] dash = { 20, 23, 0, 0, 24, 1, 0, 17, 0, 21, 0, 25, 0, 15, 11, 0, 0, 0, 0, 22, 13, 0, 0, 10, 0, 0, 0 };
int[] dot = { 5, 18, 0, 0, 2, 9, 0, 26, 0, 19, 0, 3, 0, 7, 4, 0, 0, 0, 12, 8, 14, 6, 0, 16, 0, 0, 0 };
char[] letter = { ' ', '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' };
String[] morseCode = { " ", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-",
".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--",
"--.." };
boolean programEnd = false;
while (!programEnd) {
displayMenu();
String menuOption = scan.next();
if (menuOption.equalsIgnoreCase("r")) {
receiveMorseCode(dash, letter, dot);
} else if (menuOption.equalsIgnoreCase("s")) {
sendMorseCode(morseCode);
} else if (menuOption.equalsIgnoreCase("x")) {
programEnd = true;
}else {
System.out.println("That was an Incorrect Input");
}
}
}
Python
# Currently only supports lowercase letters & prevents invalid characters. Needs modifying to support numbers.
def SendMorseCode(MorseCode):
Error = True # Input validation
while Error: # Repeat the code in this section until input is valid
Error = False # Assume no errors until one is detected
PlainText = input("Enter your message (uppercase letters and spaces only): ")
PlainTextLength = len(PlainText)
MorseCodeString = EMPTYSTRING
for i in range(PlainTextLength):
PlainTextLetter = PlainText[i]
if PlainTextLetter == SPACE:
Index = 0
else:
Index = ord(PlainTextLetter.upper()) - ord('A') + 1 # .upper() added to support lowercase characters
try: # Attempt to find morse code for current character
CodedLetter = MorseCode[Index]
MorseCodeString = MorseCodeString + CodedLetter + SPACE
except: # Has been an issue finding morse code for character - inform user of this & re-run loop to allow a new input
print("Invalid character in message.")
Error = True # Set error to true so loop re-runs
break # Break for loop to go back to start of Error loop (and ask for a new input)
print(MorseCodeString)
VB.NET
使用户无需在文件名中添加 '.txt' 扩展名的代码
C#
FileName = FileName.Contains(".txt") ? FileName : FileName + ".txt";
Delphi/Pascal
Function GetTransmission(): String;
var
FileName, FileNameOriginal: String;
FileHandle: Textfile;
Transmission: String;
begin
write('Enter file name: ');
readln(FileNameOriginal); {Variable was originally set as FileName but was changed for Concentrate}
FileName := Concat(FileNameOriginal,'.txt');
Java
static void sendMorseCode(String[] morseCode) throws IOException
{
Console.write("Enter your message (letters and spaces only): ");
String plainText = Console.readLine();
plainText = plainText.toUpperCase();
int plainTextLength = plainText.length();
String morseCodeString = EMPTYSTRING;
int index;
for (int i = 0; i < plainTextLength; i++)
{
char plainTextLetter = plainText.charAt(i);
if (plainTextLetter == SPACE)
{
index = 0;
}
else
{
index = (int)plainTextLetter - (int)'A' + 1;
}
String codedLetter = morseCode[index];
morseCodeString = morseCodeString + codedLetter + SPACE;
}
Console.writeLine(morseCodeString);
Save(morseCodeString);
}
public static void Save(String pop) throws IOException {
System.out.println("Enter file name: ");
Scanner scan = new Scanner(System.in);
String f = scan.next();
FileWriter file = new FileWriter(f+".txt", true);
PrintWriter print = new PrintWriter(file);
print.println(pop);
print.flush();
print.close();
}
Python
def GetTransmission():
FileName = input("Enter file name: ")
if FileName[-4:] != '.txt': # If last 4 characters match .txt - the 4 spaces appended to the start of string are to prevent the string being shorted than the indexes being checked
FileName += '.txt' # Append .txt to end of file name
try:
FileHandle = open(FileName, 'r')
Transmission = FileHandle.readline()
FileHandle.close()
Transmission = StripLeadingSpaces(Transmission)
if len(Transmission) > 0:
Transmission = StripTrailingSpaces(Transmission)
Transmission = Transmission + EOL
except:
ReportError("No transmission found")
Transmission = EMPTYSTRING
return Transmission
VB.NET
Function GetTransmission() As String
Dim Filename As String
Dim Transmission As String
Console.Write("Enter file name: ")
Try
Filename = Console.ReadLine()
Filename = Filename + ".txt"
Dim Reader As New StreamReader(Filename)
Transmission = Reader.ReadLine
Reader.Close()
Transmission = StripLeadingSpaces(Transmission)
If Transmission.Length() > 0 Then
Transmission = StripTrailingSpaces(Transmission)
Transmission = Transmission + EOL
End If
Catch
ReportError("No transmission found")
Transmission = EMPTYSTRING
End Try
Return Transmission
End Function
将翻译后的代码保存到文本文件的代码
C#
// Add SaveToFile(MorseCodeString) to last line of the SendMorseCode() subroutine, and also define the following subroutines:
private static void SaveToFile(string MorseCodeString) // ADDED - SAVE TO FILE
{
Console.WriteLine("Would You like to save the message to a file (Y/N)?");
string SaveChoice = Console.ReadLine(); // Check whether user wants to save to file
if (SaveChoice[0] == 'y' || SaveChoice[0] == 'Y') // [0] to only account for first character of input (both cases checked)
{
try
{
Console.WriteLine("Enter the name of the file to save the message to: ");
string FileName = Console.ReadLine(); // User input file name
if (!FileName.Contains(".txt")) // If it doesn't contain '.txt' then add the ".txt" to FileName
{
FileName += ".txt"; // Append .txt if not present
}
StreamWriter FileSaver = new StreamWriter(FileName); // Open file in write mode (new StreamWriter)
FileSaver.Write(MorseCodeString); // Write the MorseCodeString to the File chosen
FileSaver.Close();
}
catch
{
ReportError("Error when writing to file."); // Error handling message
}
Console.WriteLine("File successfully written");
}
}
Delphi/Pascal
Procedure SaveMorseToFile(MorseString : string); //added to save morse
var
FileMorse:TextFile;
begin
AssignFile(FileMorse, 'MorseFile.txt');
try
rewrite(FileMorse);
writeln(FileMorse, MorseString);
CloseFile(FileMorse);
except
on E: exception do
writeln ('Exception: ', E.Message);
end;
end;
Procedure SendMorseCode(MorseCode : Array of String);
var
PlainText, MorseCodeString, CodedLetter : String;
PlainTextLength, i, Index : Integer;
PlainTextLetter : Char;
begin
write('Enter your message (uppercase letters and spaces only): ');
readln(PlainText);
PlainTextLength := length(PlainText);
MorseCodeString := EMPTYSTRING;
for i := 1 to PlainTextLength do
begin
PlainTextLetter := PlainText[i];
if PlainTextLetter = SPACE then
Index := 0
else
Index := ord(PlainTextLetter) - ord('A') + 1;
CodedLetter := MorseCode[Index];
MorseCodeString := MorseCodeString + CodedLetter + SPACE;
end;
writeln(MorseCodeString);
SaveMorseToFile(MorseCodeString);//Saves it to a file
writeln('Saved to MorseFile.txt');
end;
Java
static void write(String morseCodeString) throws IOException
{
FileWriter fw = new FileWriter ("morse.txt");
PrintWriter output = new PrintWriter (fw);
output.println(morseCodeString);
output.close();
output.flush();
System.out.println("Printed in morse.txt");
}
Python
# Add SaveToFile(MorseCodeString) to last line of the SendMorseCode() subroutine, and also define the following subroutines:
def SaveToFile(MorseCodeString): # ADDED - SAVE TO FILE
ShouldSave = input("Would You like to save the message to a file (Y/N)?") # Check whether user wants to save to file
if ShouldSave[0].lower() == 'y': # .lower to make casing irrelevant, [0] to only account for first character (e.g. yes will also be accepted)
try:
FileName = input("Enter the name of the file to save the message to: ") # User input file name
if FileName[-4:].lower() != '.txt': # Check if file extension is .txt. The ' ' at start is 4 spaces in order to prevent error from index not existing (if file name was under 4 characters)
FileName += '.txt' # Append .txt if not present
FileHandle = open(FileName, 'w') # Open file in write mode
FileHandle.write(EncodeMorseCode(MorseCodeString)) # Write the encoded message to file
FileHandle.close()
except:
ReportError("Error when writing to file.") # Error handling
def EncodeMorseCode(MorseCode): # Function to convert morse code to format saved in file
Output = MorseCode.replace('-', '=== ').replace('.', '= ').replace(' ', ' ').replace(' ', ' ') # Format message to required format
return Output # Return message to be saved to file
VB.NET
输出列表中所有字符及其摩尔斯电码表示形式。
C#
// NEW SUBROUTINE- Letter and MorseCode lists are passed as parameters/arguments
private static void ListMorseCode(char[] Letter, string[] MorseCode)
{
for (int index = 0; index < Letter.Length; index++) // for loop - loops through all elements in the Letter Array
{
Console.WriteLine(Letter[index] + " " + MorseCode[index]); // Output the text character, followed by a few spaces, and then the Morse code representation
}
}
// AMENDED SUBROUTINE
private static void DisplayMenu()
{
Console.WriteLine();
Console.WriteLine("Main Menu");
Console.WriteLine("=========");
Console.WriteLine("R - Receive Morse code");
Console.WriteLine("S - Send Morse code");
Console.WriteLine("L - List Morse code characters"); // Added - display menu option for this modification
Console.WriteLine("X - Exit program");
Console.WriteLine();
}
// AMENDED SUBROUTINE
private static void SendReceiveMessages()
{
int[] Dash = new int[] { 20, 23, 0, 0, 24, 1, 0, 17, 0, 21, 0, 25, 0, 15, 11, 0, 0, 0, 0, 22, 13, 0, 0, 10, 0, 0, 0 };
int[] Dot = new int[] { 5, 18, 0, 0, 2, 9, 0, 26, 0, 19, 0, 3, 0, 7, 4, 0, 0, 0, 12, 8, 14, 6, 0, 16, 0, 0, 0 };
char[] Letter = new char[] { ' ', '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' };
string[] MorseCode = new string[] { " ", ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
bool ProgramEnd = false;
string MenuOption = EMPTYSTRING;
while (!ProgramEnd)
{
DisplayMenu();
MenuOption = GetMenuOption();
if (MenuOption == "R")
{
ReceiveMorseCode(Dash, Letter, Dot);
}
else if (MenuOption == "S")
{
SendMorseCode(MorseCode);
}
else if (MenuOption == "X")
{
ProgramEnd = true;
}
else if (MenuOption == "L") // Added - if menu option selected is the 'L' (list Morse code)
{
ListMorseCode(Letter, MorseCode); // Run ListMorseCode subroutine, passing lists Letter and MorseCode
}
}
}
Delphi/Pascal
Procedure DisplayMenu();
begin
writeln;
writeln('Main Menu');
writeln('=========');
writeln('R - Receive Morse code');
writeln('S - Send Morse code');
writeln('L - List Morse code characters');//Added menu option for this
writeln('X - Exit program');
writeln;
end;
Procedure ListCharacters(Letter:Array of char; MorseCode:Array of String); //new procedure for listing
var
z : integer;
begin
for z:=0 to 26 do
writeln(Letter[z],' ',MorseCode[z]);
end;
Procedure SendReceiveMessages();
const
Dash: array[0..26] of Integer = (20,23,0,0,24,1,0,17,0,21,0,25,0,15,11,0,0,0,0,22,13,0,0,10,0,0,0);
Dot : array[0..26] of Integer = (5,18,0,0,2,9,0,26,0,19,0,3,0,7,4,0,0,0,12,8,14,6,0,16,0,0,0);
Letter : array[0..26] of Char= (' ','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');
MorseCode : array[0..26] of String= (' ','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..');
var
ProgramEnd : Boolean;
MenuOption : String;
begin
ProgramEnd := False;
while not(ProgramEnd) do
begin
DisplayMenu();
MenuOption := GetMenuOption();
if MenuOption = 'R' then
ReceiveMorseCode(Dash, Letter, Dot)
else if MenuOption = 'S' then
SendMorseCode(MorseCode)
else if MenuOption = 'X' then
ProgramEnd := True
else if MenuOption = 'L' then
ListCharacters(Letter, MorseCode); //Added to lead to new procedure
end;
end;
Java
Python
# Added subroutines
def ListMorseCode(Letter, MorseCode): # New subroutine - Letter and MorseCode lists are passed as parameters
for Pos in range(len(Letter)): # Loop through all positions in the length of the list
print(Letter[Pos]+" "+MorseCode[Pos]) # Output the text character, followed by a few spaces, and then the Morse code representation
# Existing modified subroutines
def DisplayMenu():
print()
print("Main Menu")
print("=========")
print("R - Receive Morse code")
print("S - Send Morse code")
print("L - List Morse code characters") # Added - display menu option for this modification
print("X - Exit program")
print()
def SendReceiveMessages():
Dash = [20,23,0,0,24,1,0,17,0,21,0,25,0,15,11,0,0,0,0,22,13,0,0,10,0,0,0]
Dot = [5,18,0,0,2,9,0,26,0,19,0,3,0,7,4,0,0,0,12,8,14,6,0,16,0,0,0]
Letter = [' ','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']
MorseCode = [' ','.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']
ProgramEnd = False
while not ProgramEnd:
DisplayMenu()
MenuOption = GetMenuOption()
if MenuOption == 'R':
ReceiveMorseCode(Dash, Letter, Dot)
elif MenuOption == 'S':
SendMorseCode(MorseCode)
elif MenuOption == 'X':
ProgramEnd = True
elif MenuOption == 'L': # Added - if menu option selected is the 'L' (list Morse code)
ListMorseCode(Letter, MorseCode) # Run ListMorseCode subroutine, passing lists Letter and MorseCode
VB.NET
问题描述
C#
Delphi/Pascal
Procedure SendMorseCode(MorseCode : Array of String);
var
PlainText, MorseCodeString, CodedLetter,x : String;
PlainTextLength, i, Index : Integer;
PlainTextLetter : Char;
continue : integer;
begin
continue:= 0;
repeat
write('Enter your message (uppercase letters and spaces only): ');
readln(PlainText);
PlainTextLength := length(PlainText);
MorseCodeString := EMPTYSTRING;
for i := 1 to PlainTextLength do
begin
PlainTextLetter := PlainText[i];
if PlainTextLetter = SPACE then
Index := 0
else
Index := ord(PlainTextLetter) - ord('A') + 1;
CodedLetter := MorseCode[Index];
MorseCodeString := MorseCodeString + CodedLetter + SPACE;
end;
writeln(MorseCodeString);
write('Continue (Y or N): ');
readln(x);
if (x = 'Y') or (x ='y') then //start of continue
continue:= 0
else if (x = 'N') or (x = 'n') then
continue:= 1
else
begin
writeln('Interpreting answer as no');//could be made to loop if needed
continue:=1;
end;
until continue = 1;
end;
Java
Python
def SendMorseCode(MorseCode):
Continue = 0
while Continue != 1:
PlainText = input("Enter your message (uppercase letters and spaces only): ").upper()
PlainTextLength = len(PlainText)
MorseCodeString = EMPTYSTRING
for i in range(PlainTextLength):
PlainTextLetter = PlainText[i]
if PlainTextLetter == SPACE:
Index = 0
else:
Index = ord(PlainTextLetter) - ord('A') + 1
CodedLetter = MorseCode[Index]
MorseCodeString = MorseCodeString + CodedLetter + SPACE
print(MorseCodeString)
x = input("Continue Y/N?: ")
if x == "Y" or x == "y":
Continue = 0
elif x == "N" or x == "n":
Continue = 1
else:
print("Interpreting answer as no")
Continue = 1
VB.NET
这将接受小写字符的输入
C#
// AMENDED SUBROUTINE - Allows Lowercase values in Send string now. (ASCII values used)
private static void SendMorseCode(string[] MorseCode)
{
Console.Write("Enter your message (uppercase letters and spaces only): ");
string PlainText = Console.ReadLine();
int PlainTextLength = PlainText.Length;
string MorseCodeString = EMPTYSTRING;
char PlainTextLetter = SPACE;
int Index = 0;
int ascii; // declare new value 'ascii' to store that value.
for (int i = 0; i < PlainTextLength; i++)
{
PlainTextLetter = PlainText[i];
if (PlainTextLetter == SPACE)
{
Index = 0;
}
else
{
if ((int)PlainTextLetter >= 97) // if ASCII Value of that letter is 97 or above, it is assumed to be lowercase.
ascii = (int)PlainTextLetter - 32; // if lowercase then subtract 32 from its ASCII value
else
ascii = (int)PlainTextLetter; // else it is uppercase, then use that ASCII value.
Index = ascii - (int)'A' + 1; // use the 'ascii' value to calculate, just incase lowercase has been used.
}
string CodedLetter = MorseCode[Index];
MorseCodeString = MorseCodeString + CodedLetter + SPACE;
}
Console.WriteLine(MorseCodeString);
}
Delphi/Pascal
Procedure SendMorseCode(MorseCode : Array of String);
var
PlainText, MorseCodeString, CodedLetter : String;
PlainTextLength, i, Index, assci : Integer;
PlainTextLetter : Char;
begin
write('Enter your message (uppercase letters and spaces only): ');
readln(PlainText);
PlainTextLength := length(PlainText);
MorseCodeString := EMPTYSTRING;
for i := 1 to PlainTextLength do
begin
PlainTextLetter := PlainText[i];
if PlainTextLetter = SPACE then
Index := 0
else
begin //added to allow lower case letters
if ord(PlainTextLetter) >= 97 then
assci:= ord(PlainTextLetter) - 32
else
assci:= ord(PlainTextLetter);
Index := assci - ord('A') + 1;
end; //should work
CodedLetter := MorseCode[Index];
MorseCodeString := MorseCodeString + CodedLetter + SPACE;
end;
writeln(MorseCodeString);
end;
Delphi/Pascal
write ('This is a question: ');
readln(Variable);
Variable := AnsiUpperCase(Variable);
{This can be added for the MenuOption (in GetMenuOption) and Plaintext (in SendMorseCode)}
Java
static char getMenuOption() {
boolean valid = false;
char menuOption = ' ';
while(!valid) {
String option = EMPTYSTRING;
Console.write("Enter menu option");
try {
option = Console.readLine();
} catch (Exception e) {
System.out.println("Invalid input");
}
if (option.equalsIgnoreCase("R"))
menuOption = 'R'; valid = true;
if (option.equalsIgnoreCase("S"))
menuOption = 'S'; valid = true;
if (option.equalsIgnoreCase("X")) {
menuOption = 'X'; valid = true;
}
else if (!valid) {
System.out.println("Invalid input");
}
}
Python
def SendMorseCode(MorseCode):
PlainText = input("Enter your message (uppercase letters and spaces only): ").upper()#Changed
PlainTextLength = len(PlainText)
MorseCodeString = EMPTYSTRING
for i in range(PlainTextLength):
PlainTextLetter = PlainText[i]
if PlainTextLetter == SPACE:
Index = 0
else:
Index = ord(PlainTextLetter) - ord('A') + 1
CodedLetter = MorseCode[Index]
MorseCodeString = MorseCodeString + CodedLetter + SPACE
print(MorseCodeString)
def GetMenuOption():
MenuOption = EMPTYSTRING
while len(MenuOption) != 1:
MenuOption = input("Enter your choice: ").upper()#Changed
return MenuOption
VB.NET
Sub SendMorseCode(ByVal MorseCode() As String)
Dim PlainText As String
Dim PlainTextLength As Integer
Dim MorseCodeString As String
Dim PlainTextLetter As Char
Dim CodedLetter As String
Dim Index As Integer
Console.Write("Enter your message (uppercase letters and spaces only): ")
PlainText = Console.ReadLine()
PlainTextLength = PlainText.Length()
MorseCodeString = EMPTYSTRING
For i = 0 To PlainTextLength - 1
PlainTextLetter = PlainText(i)
If PlainTextLetter = SPACE Then
Index = 0
Else
Index = Asc(PlainTextLetter)
If Index > 96 And Index < 123 Then
Index -= 32
End If
Index = Index - Asc("A") + 1
End If
CodedLetter = MorseCode(Index)
MorseCodeString = MorseCodeString + CodedLetter + SPACE
Next
Console.WriteLine(MorseCodeString)
SaveMorseCode(MorseCodeString)
End Sub