gpt4 book ai didi

java - 帮助完成莫尔斯电码 Java 作业!

转载 作者:行者123 更新时间:2023-11-30 05:04:34 24 4
gpt4 key购买 nike

摩尔斯电码翻译的值不断返回null,我已尽我所能来修复它。我们仅限于在此作业中使用数组。我可以做什么来纠正它?

import javax.swing.JOptionPane;
import java.util.*;
import java.io.*;

public class morseCodeTest
{
public static void main(String[] args)throws IOException
{
String userInput;
final String SENTINEL = "0";//for exiting program when entered

//object creation
Translate text = new Translate();

//getting user input to be translated
do
{
userInput = JOptionPane.showInputDialog("Please enter what you wish to translte to Morse code (no punctuation).");
String compare = userInput.toUpperCase();
String[] codedText = new String[compare.length()];

codedText = text.translateHere(compare);
text.toString(userInput, codedText);
}while(!userInput.equals(SENTINEL));
}//end main
}//end class

class Translate
{
public Translate()
{
}//end default constructor

public String[] translateHere(String s)throws IOException
{
String compare = s, codedLine = ""; //userInput toUpperCase
int length = compare.length(); //length of userInput
String line, file = "Morse.txt";// variable holding file name and variable for each letter/number
char code;

//Constants
final int MAX = 36;

//Arrays
char[] morseLetter = new char[MAX];
String[] morseCode = new String[MAX];
String[] newMessage = new String[length];

//putting user input in a character array;
char[] userLetters = compare.toCharArray();

//object creation
File openFile = new File(file);
Scanner inFile = new Scanner(openFile);

//for loop that will read data from the Morse.txt file
for(int i = 0; i < MAX; i++)
{
while(inFile.hasNext())
{
line = inFile.next();
code = (char)line.charAt(0);
morseLetter[i] = code;
morseCode[i] = inFile.next();
}//end nested while loop
}//end for loop

for(int j = 0; j < length; j++)
{
for(int k = 0; k < MAX; k++)
{
if(userLetters[j] == morseLetter[k])
{
newMessage[j] = morseCode[k];
}
}//end nested for loop
}//end for loop
return newMessage;
}//end method that completes translateion

public String toString(String a, String[] b)
{
String input = a;
String[] coded = b;
String[] encoded = new String[input.length()];
//JOptionPane.showMessageDialog(null, "Original Text: " + input + "\nCoded Text: " + coded);
for(int l = 0; l <input.length(); l++)
{
encoded[l] = coded[l];
}
String str = "";
System.out.print(Arrays.toString(encoded));
return str;
}//end toString method
}//end Translate Class

摩尔斯电码文本文件包含以下内容:

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

最佳答案

您的 Translate.toString 方法将始终返回空字符串,因为这是您分配给 str 变量的唯一内容。

关于java - 帮助完成莫尔斯电码 Java 作业!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5532571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com