Reputation: 25
I've created the following:
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]);
}
What I would like to know is how to get the value of the corresponding position based on user input. I'm learning, so I just want the piece on how to get, as an example, .-
back when "a"
is entered.
Upvotes: 1
Views: 68
Reputation: 1308
First of all you have to read the letter as the String object. Then you can just iterate through your array and when we find what we are looking for - just print it and break the loop:
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;
}
Upvotes: 1
Reputation: 12233
You can also use Hash tables, since they've already given sample above of HashMap/Map:
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("a", ".-");
table.put("b", "-...");
It is also synchronized and thread safe unlike HashMaps, albeit is a smidgen slower for bigger data sets.
Upvotes: 1
Reputation: 4039
Simply iterate over you array and compare the 0th element at each position with the character you are looking for.
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);
But as the other answer says you should use a map that whould fit perfect for this task.
Upvotes: 3
Reputation: 479
Or a map of string arrays
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];
Upvotes: 1
Reputation: 520908
You should consider using a Map
instead of a two dimensional array for this problem:
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");
Upvotes: 2