gpt4 book ai didi

java - 带文本文件和比较索引的摩尔斯电码

转载 作者:行者123 更新时间:2023-12-01 11:39:27 26 4
gpt4 key购买 nike

大家。我的摩尔斯电码出现问题。我正在尝试将英文消息或文本(如“A”)转换为莫尔斯电码“.-”

但是,我的转换方法遇到了问题。当我运行我的代码时,我收到了找到的消息,但是,我也收到了我读入的整个莫尔斯电码。

我的老师告诉我我需要比较索引,这样我就可以打印莫尔斯电码的值。但是,我仍然对逻辑抱有疑虑。

这是我到目前为止得到的:

public class MorseCode {

public static ArrayList<String> alpha;
public static ArrayList<String> codes;

/**
* This Constructor actually imports the list of Morse Code Characters and adds it to an ArrayList.
*/
public MorseCode() throws IOException
{
String token = "";
Scanner inFile = new Scanner(new File("morsecode.txt"));

codes = new ArrayList<String>();
codes.add(".-");
codes.add("-...");
codes.add("-.-.");

while(inFile.hasNext())
{
token = inFile.nextLine();
System.out.println(token);
}
inFile.close();
}

public static void alpha () throws IOException
{
Scanner inFile = new Scanner(new File("alphabet.txt"));
String cake = "";

alpha = new ArrayList<String>();
alpha.add("A");
alpha.add("B");
alpha.add("C");

while(inFile.hasNext())
{
cake = inFile.nextLine();
System.out.println(cake);
}
inFile.close();
}

public static ArrayList<String> getMorse()//ArrayList<String> codes
{
ArrayList codes = new ArrayList<String>();
return codes;
}

public static ArrayList<String> getAlpha()//ArrayList<String> alpha
{
ArrayList alpha = new ArrayList<String>();
return alpha;
}

public static void Morse ( String token)
{
for( String m : codes)
{
token = m;
System.out.println(m);
}
}

public static void Alpha(String cake)
{
for( String a : alpha)
{
cake = a;

System.out.println(a);
}
}

public static String convertCode (String myMessage)
{
alpha = new ArrayList<String>();
String myLetter = "";
String cake = "";
int myindex = 0;
for(int index = 0; index < myMessage.length(); index++)
{
myLetter = myMessage.substring(index,index + 1);

for( int in = 0; in < alpha.size(); in++)
{
if(alpha.get(in).equals(myLetter))
{
index = in;
}
cake += codes.get(in);
System.out.println(cake);
}
}

return cake;
}
}

最佳答案

Doctuer 所说的是真的,您似乎过于频繁地重置值。

这个转换函数应该可以工作,它会返回一个字符串(以莫尔斯电码编码)给定一个正常的英语单词。

    public static String encodeMessage(String message) {

String encodedMessage = "";

// Loop through the String
for(int i = 0; i < message.length(); i++) {

// Get each Character in String format
String character = String.valueOf(message.charAt(i));

// Look for the index of the Character in the Alphabet List
for(int j = 0; j < alphabet.size(); j++) {

// If we find a match use the Index to get the corresponding Morse Value
if(alphabet.get(j).equals(character)) {

encodedMessage += code.get(j);

// Move onto the next Letter
break;
}
}
}

// Returns only the Encoded Message
return encodedMessage;
}
}

关于java - 带文本文件和比较索引的摩尔斯电码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29662944/

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