VanDal VanDal - 2 months ago 7
Java Question

Beginner - Java 2D Array

Newbie question on Java.

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.

Thanks for the help!

Answer

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.