我已经进行了彻底的搜索,但是在此站点上找不到满意的答案。
我的任务是将一串英文大写字符转换为莫尔斯电码。

我的计划是遍历字符串,并使数组(i)的索引与带有摩尔斯电码索引的字母匹配。

import java.util.Scanner;

public class Morse {
    public static void main(String[]arg) {
        Scanner Read = new Scanner(System.in);
        String uinput, res = "";

        String[] Eng = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","X","Y","Z"};
        String[] mors = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};

        System.out.println("Ange den text du vill översätta till Morse-kod: ");
        uinput = Read.nextLine();  //uinput = user input
        for (int i = 0; i < uinput.length(); ) {
            res = res + (mors.charAt(Eng.indexOf(i)));
        }
        System.out.println(res);
    }
}


当我运行此程序时,我收到错误消息:

Morse.java:16: error: cannot find symbol
  res = res + (mors.charAt(Eng.indexOf(i)));
                                  ^
  symbol:   method indexOf(int)
  location: variable Eng of type String[]
1 error

最佳答案

你有两个问题。

首先是您没有查看uinput本身的字符。您需要遍历这些字符以构建输出。

第二个原因是Java的内置数组没有indexOf()方法。您可以选择以下几种方法:


您可以自己写一个。
您可以将Eng数组的内容放入List(可能是ArrayList)中,该列表确实具有indexOf()方法。
由于Java字符也是数字,因此您可以将字母本身用作莫尔斯电码数组的索引。 (但是请注意大小写问题,并注意“ A”的数值不为0。)

09-25 16:14