-3

i'm beginner Java. My code is to convert Morse code entered from the keyboard and output as meaningful characters. This is just a 3-letter "A" "B" "C" test but when I ran it had an error. Help me, please !

import java.util.*;
import java.io.*;

 public class Main {
 public static void main (String[] args) {
    String [][] Morse = new String[60][2];

        Morse[0][0] = "A" ; Morse[0][1] = ".-" ; 
        Morse[1][0] = "B" ; Morse[1][1] = "-...";
        Morse[2][0] = "C" ; Morse[2][1] = "-.-.";

    Scanner ip = new Scanner(System.in);
    String s = ip.nextLine();
    String [] op = s.split(" ");
    for (int i = 0 ; i <  60 ; i++) 
        if ( op[i] == Morse[i][1] ) System.out.print(" "+Morse[i][0]);
    }
}
  • Welcome to stack overflow, your `Morse` Object is `null` in some cases making it impossible to retrieve information. Usually you should google the `ArrayIndexOutOfBounds` to see what it is. You are iterating an `Array` with `null` object reference. – Phill Alexakis May 07 '20 at 08:57

2 Answers2

1

Welcome to stack overflow, please go though the How To Ask A Question before you make post.

I will list some problems and their causes as you are getting started with Java.

Here is a helpful link with some Data Structures to approach an Object Oriented use case scenario.

Regarding your code

First of all take a look at How To Split A String In Java

  • For Input: "A"
 String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] is null because there is no space to split it with

  • For Input: "A (1 space)"
 String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] No "Space" to add to op[1]

  • For Input: "A (1+ spaces)"
 String [] op = s.split(" ");
//op[0] contains the A,B,C etc.
//op[1] Still no "Space" to add to op[1]

Solution:

Change if ( op[i] == Morse[i][1] ) to if ( op[0] == Morse[i][1] )

Remember the input is always at the 0 index of the op Array

For me, it doesn't trigger an ArrayOutOfBoundsException you can continue with implementing your logic in your case senario.

Phill Alexakis
  • 1,449
  • 1
  • 12
  • 31
0

You can use a data structure called HashMap, check the following code

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Sol {
    public static void main(String[] args) {
        Map<String, String> morseToText = new HashMap<>();
        morseToText.put(".-", "A");
        morseToText.put("-...", "B");
        morseToText.put("-.-.", "C");

        Scanner ip = new Scanner(System.in);
        String s = ip.nextLine();
        String[] op = s.split(" ");
        for (String s1 : op) {
            System.out.print(morseToText.get(s1));
        }
    }
}
Kavin Eswaramoorthy
  • 1,595
  • 11
  • 19