1

I'm creating a program that reads in something written in Morse code and translates it to English, I first have to read in the first number for all the data sets the the second which stands for how much data is in the first data set, then i read in the String with which is th morse code. I decided to use a Switch statement for this program but everytime i complile it it says "incompatible types" for switch(morse). FYI This only apart off my code..

<pre>
import java.io.*;
import java.util.*;
import static java.lang.System.*;

public class G{

    public static void main(String[] args)throws IOException
        {
            Scanner scan = new Scanner(new File("G.txt"));
            int times = scan.nextInt();
            times=scan.nextInt();
            for(int i=0; i<times; i++){

                 String morse = scan.nextLine();
                 switch(morse){
                    case ".- ":
                        System.out.print( "a");
                        break;
                    case "-… ":
                        System.out.print( "b");
                        break;
                    case "-.-. ":
                        System.out.print( "c");
                        break;
        }
    }
}
<code>

This is my input file(ignore the spaces between each line) 2

4

-..

..-

-..

.

4

-..

.

.-..

.--.

2 Answers2

2

Switch on strings was added in Java 7. If you are using Java 6 or lower you should update your buildpath settings to be Java 7, or upgrade your compiler, JDK, and JRE.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • (Given that the question is tagged java-7, it looks like at least the OP *thinks* he's using it) – Dennis Meng Oct 20 '13 at 00:43
  • @DennisMeng I doubt he *is* using it. – nanofarad Oct 20 '13 at 00:43
  • Sure, but if we think it's a "I thought I was using Java 7, but looks like i'm not" issue, wouldn't the answer be structured differently from if it were a "I know I'm not using Java 7 or higher" issue? – Dennis Meng Oct 20 '13 at 00:44
0

An ugly, but possible solution is to switch based on each character like

switch(morse[0]) {  
case '.':  
    switch(morse[1]) {  
        case '-':  
        switch(morse[2]) {  
            case '.':  
                system.out.print("x");  
                break;  
            case '-':  
                system.out.print("y");  
                break;  
        }  
    }  
}
Jacob Minshall
  • 1,044
  • 9
  • 15