gpt4 book ai didi

java - 将短语中字符的字符串值转换为莫尔斯电码的类

转载 作者:行者123 更新时间:2023-12-01 13:07:25 24 4
gpt4 key购买 nike

我不明白为什么我能够使用非常相似的循环打印这些字符串值,但它不会像我假设的替换方法那样遍历并替换字母。这是输出: aforementioned output——但正如您所看到的,本应翻译的短语并未被翻译。我打印彼此对齐的数组和值。输入是重印的(未更改),尽管它是要调整为莫尔斯电码的字符串值。如果有人能够解释问题所在,我将不胜感激。

.txt 文件中的文本值也如下:

.-
-...
-.-.
-..
.
..-.
--.
....
..
.---
-.-
.-..
--
-.
---
.--.
--.-
.-.
...
-
..-
...-
.--
-..-
-.--
--..
.----
..---
...--
....-
.....
-....
--...
---..
----.
-----

然后是类(class):

import java.util.*;
import java.io.*;
public class MorseCode
{
public static void main(String []args) throws IOException
{
String characters[] = {"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"};
String morseCharacter[] = new String[(characters.length)];

Scanner in = new Scanner(System.in);
System.out.println();

System.out.print("Enter a phrase you wish to translate to morse: ");
String entry = in.nextLine();

File fileName1 = new File("morseCode.txt");

Scanner inFile = new Scanner(fileName1);

int counter1 = 0;
while(inFile.hasNextLine() && counter1 < (characters.length))
{
morseCharacter[counter1] = inFile.nextLine();
morseCharacter[counter1] += " ";
counter1++;
}

String result = "";

for(int x = 0; x < (morseCharacter.length); x++)
{
result = entry.replaceAll(characters[x], morseCharacter[x]);
}

for(int x = 0; x < (morseCharacter.length); x++)
{
System.out.println(characters[x] + " = " + morseCharacter[x]);
}

System.out.println(result);
}
}

最佳答案

您仅应用最后一个字符,因为您始终从条目替换,而不是从之前的结果替换。

试试这个:

    String result = entry;
// ^^^^^

for(int x = 0; x < (morseCharacter.length); x++)
{
result = result.replaceAll(characters[x], morseCharacter[x]);
} // ^^^^^^

关于java - 将短语中字符的字符串值转换为莫尔斯电码的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23167085/

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