【发布时间】:2015-02-17 22:22:46
【问题描述】:
我已彻底搜索,但在此站点上找不到满意的答案。 我的任务是将一串英文大写字符翻译成莫尔斯电码。
我的计划是遍历字符串并将数组中 (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
【问题讨论】:
-
显然,您的问题是您试图将方法
indexOf应用于数组而不是String。 -
Eng是Strings 的(名称不佳)数组,而不是String。因此,它没有编译器通知您的indexOf方法。您可能想使用Map。 -
查看indexOf 的文档。它需要一个字符或字符串作为参数。
-
尝试使用
HashMap做你想做的事。字符串数组是不好的方法。