Before I begin, I am a novice programmer having only been doing this for about a day.
How do I get my program to continue reading my input after an input has been fulfilled? for the below code, which is for a morse code to english translator I am trying to make, when I input morse, for example .-, it gives me the correct output, A. But when I combine morse letters, example .--..., which should be AB, the else statement activates. What should I do?
import java.util.Scanner;
public class MorseTranslator {
public static void main(String[] args) {
System.out.println("Please enter morse code you wish to translate.");
Scanner sc =new Scanner(System.in);
String morse = sc.next();
if (morse.equals(" ")) {
System.out.print(" ");
}
if (morse.equals(".-")){
System.out.print("A");
}
if (morse.equals("-...")){
System.out.print("B");
}
if (morse.equals("-.-.")){
System.out.print("C");
}
if (morse.equals("-..")){
System.out.print("D");
}
if (morse.equals(".")){
System.out.print("E");
}
if (morse.equals("..-.")){
System.out.print("F");
}
else System.out.println("Please input morse code.");
}
}
String.equals() compares complete strings, so .--... will never be equals to .- , so what you need is to 'look for' inside the morse String, using String.indexOf()
if(morse.indexOf(".-")!=-1){
System.out.print("A");
//need more magic here
}
now you need to 'substract' or takeout those two characters from the morse string, and repeat the searching with a loop.
if(morse.indexOf(".-")!=-1){
System.out.print("A");
morse=morse.substring(morse.indexOf(".-")+2); // where 2 morse characters
continue; //your hypothetical loop
}
if(morse.indexOf("-...")!=-1){
System.out.print("B");
morse=morse.substring(morse.indexOf("-...")+4); // where 4 morse characters
continue; //your hypothetical loop
}
...
don't forget to loop until there's no more data to process