我创建了以下内容:
import java.util.*;
public class morse5 {
public static void main(String [] args)
{
//Declare Variables
String [][] myIndexAlphaMorse = {{"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", "-----"}, {" ", "|"}};
//Test
System.out.println(Arrays.deepToString(myIndexAlphaMorse));
System.out.println(myIndexAlphaMorse[8][0]);
}
我想知道的是如何根据用户输入获取相应位置的值。我正在学习,所以我只想知道如何在.-
输入"a"
时获取UIImageView
。
答案 0 :(得分:3)
只需遍历您的数组,并将每个位置的第0个元素与您要查找的字符进行比较。
String input = "v";
String result= "";
for(int i = 0; i < myIndexAlphaMorse.length; i++){
if(myIndexAlphaMorse[i][0].equals(input)){
result = myIndexAlphaMorse[i][1];
break;
}
}
System.out.println("morse for " + input + " = " + result);
但正如另一个答案所说,你应该使用一个适合这项任务的地图。
答案 1 :(得分:2)
对于此问题,您应该考虑使用Map
而不是二维数组:
Map<String, String> myIndexAlphaMap = new HashMap<>();
myIndexAlphaMap.put("a", ".-");
myIndexAlphaMap.put("b", "-...");
// etc.
// given user input of "a" you can access via
myIndexAlphaMap.get("a");
答案 2 :(得分:1)
或字符串数组的地图
Map<String, String[]> myIndexAlphaMap = new HashMap<String, String[]>();
myIndexAlphaMap.put("a", new String {".","-"});
myIndexAlphaMap.put("b", new String {"-",".","."});
// given user input of "a" you can access via
myIndexAlphaMap.get("a")[0];
答案 3 :(得分:1)
您也可以使用Hash表,因为他们已经在HashMap / Map上面给出了示例:
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("a", ".-");
table.put("b", "-...");
与HashMaps不同,它也是同步和线程安全的,虽然对于更大的数据集来说,它的速度更慢。
答案 4 :(得分:1)
首先,您必须将该字母作为String对象读取。然后你可以遍历你的数组,当我们找到我们正在寻找的东西时 - 只需打印它并打破循环:
Scanner scanner = new Scanner(new InputStreamReader(System.in));
String letter = scanner.next();
for (int i=0; i<myIndexAlphaMorse.length; i++)
if (myIndexAlphaMorse[i][0].equals(letter)){
System.out.println(myIndexAlphaMorse[i][1]);
break;
}