java morse code probelm using constructors - java

I have a java morse code assignment using constructors. I got the code working but having a hard time calling the constructor.
My original code.
import java.util.Scanner;
public class morseTest {
public static void main(String[] args) {
char alphabet[] = { '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',
',', '.', '?' };
String morse[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", "--..--", ".-.-.-", "..--.." };
Scanner sc = new Scanner(System.in);
String input = sc.nextLine().toLowerCase();
char[] chars = input.toCharArray();
String str = "";
for (int i = 0; i < chars.length; i++) {
for (int index = 0; index < alphabet.length; index++) {
if (alphabet[index] == chars[i]) {
str = str + morse[index] + " ";
}
}
}
System.out.println(str);
sc.close();
}
}
I have to call and implement a method stringToMorse() from MorseCode.java from Demo.java.
import java.util.Scanner;
import java.util.*;
public class Demo {
public static void main(String[] args) {
// PLACE CODE HERE
Scanner sc = new Scanner(System.in);
String input = sc.nextLine().toLowerCase();
MorseCode message = new MorseCode(input);
System.out.println(message.stringToMorse());
}
}
import java.util.Scanner;
public class MorseCode {
private static char[] alphabet;
private static String[] morse;
private static String input;
public MorseCode() {
// PLACE CODE HERE
char alphabet[] = { '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',
',', '.', '?' };
String morse[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", "--..--", ".-.-.-", "..--.." };
}
MorseCode(String s) {
input = s;
}
public static String stringToMorse(String s) {
// PLACE CODE HERE
char[] chars = input.toCharArray();
String str = "";
for (int i = 0; i < chars.length; i++) {
for (int index = 0; index < alphabet.length; index++) {
if (alphabet[index] == chars[i]) {
str = str + morse[index] + " ";
}
}
}
return s;
}
When compiling, I got the error messsage
Demo.java:13: error: method stringToMorse in class MorseCode cannot be applied to given types;
System.out.println(message.stringToMorse());
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length
1 error

public static String stringToMorse(String s)
This method needs one argument.
While invoking message.stringToMorse() there is no argument passed to it.
Also , In code stringToMorse method is declared as static, so it can be call via className. Please refer below code changes.
public class Demo {
public static void main(String[] args) {
// PLACE CODE HERE
Scanner sc = new Scanner(System.in);
String input = sc.nextLine().toLowerCase();
System.out.println(MorseCode.stringToMorse(input));
}
}
Code for MorseCode class has an error in stringToMorse method. It is returning variable s which is nowhere declared.
import java.util.Scanner;
public class MorseCode {
private static char[] alphabet ={ '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',
',', '.', '?' };
private static String[] morse= { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..",
".---", "-.-", ".-..", "--", "-.", "---", ".---.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----",
"..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.",
"-----", "--..--", ".-.-.-", "..--.." };
public static String stringToMorse(String input) {
// PLACE CODE HERE
char[] chars = input.toCharArray();
String str = "";
for (int i = 0; i < chars.length; i++) {
for (int index = 0; index < alphabet.length; index++) {
if (alphabet[index] == chars[i]) {
str = str + morse[index] + " ";
}
}
}
return str;
}

Related

displaying the alphabet with arrays and methods [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 9 months ago.
package Exercises;
public class Challenge9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//create class instance
Challenge9 al = new Challenge9();
//call the first method
//al.returnAlphabetArray();
//call second method
char[] A = al.getAlphabetArray();
System.out.println("The letters of the alphabet are: " + A);
}
//public void returnAlphabetArray() {
//System.out.println("Read the alphabet");
//}
public char[] getAlphabetArray() { //create first method
char[] letters = {'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'};
return letters;
}
}
I want to display the letters of the alphabet but why am I getting this output after the string: "[C#3d012ddd" ?
if you don't want to hard code the alphabet
public char[] getAlphabetArray() {
char[] letters = new char[122 - 97];
for (int i = 0; i < letters.length; i++) {
letters[i] = (char) (97 + i);
}
return letters;
}
And use this to print an array
Arrays.toString(getAlphabetArray())

Use insertion sort to sort vowels at the beginning of string

Is it possible to use insertion sort algorithm to sort the vowels at the beginning of a string?
I tried a lot but I don't get it , has somebody a hint how it could be implemented or should I use an other sort algorithm?
static char[] text = "thisIsAString".toCharArray();
static void instertionSort() {
for (int i = 0; i < text.length; i++) {
char h = text[i];
int j = i - 1;
while ((j >= 0) && Character.toLowerCase(text[j]) > Character.toLowerCase(h)) {
text[j+1] = text[j];
j = j - 1;
}
text[j+1] = h;
}
}
Example: "thisIsAString" -> "AiiIghnrssStt"
You can use insertion sort for this (just like every other sort-algorithm, they are all equal. Only the time they take for sorting the field is different, but the result is always the same).
The problem in your algorithm is that you don't check whether the compared characters are vowels or upper/lower case.
This code should work:
public class StringSorter {
private static final String vowels = "aeiou";
public static void main(String[] args) {
char[] string = "thisIsAString".toCharArray();
char[] test2 = "thisIsAStringaAabBs".toCharArray();
System.out.println("unsorted: " + new String(string));
insertionSort(string);
System.out.println("sorted: " + new String(string));
System.out.println();
System.out.println("unsorted: " + new String(test2));
insertionSort(test2);
System.out.println("sorted: " + new String(test2));
}
public static void insertionSort(char[] string) {
for (int i = 1; i < string.length; i++) {
char h = string[i];
int j = i;
while ((j > 0) && isBefore(string[j - 1], h)) {
string[j] = string[j - 1];
j = j - 1;
}
string[j] = h;
}
}
private static boolean isBefore(char a, char b) {
String lowA = Character.toString(Character.toLowerCase(a));
String lowB = Character.toString(Character.toLowerCase(b));
if (vowels.contains(lowA)) {
if (vowels.contains(lowB)) {
//both are vowels
return chooseLowerCaseFirst(a, b);
}
else {
//only a is a vowel
return false;
}
}
else if (vowels.contains(lowB)) {
//only b is a vowel
return true;
}
else {
//none is a vowel
return chooseLowerCaseFirst(a, b);
}
}
private static boolean chooseLowerCaseFirst(char a, char b) {
String lowA = Character.toString(Character.toLowerCase(a));
String lowB = Character.toString(Character.toLowerCase(b));
if (lowA.equals(lowB)) {
//both are the same character
if (Character.isLowerCase(a)) {
if (Character.isLowerCase(b)) {
//both are lower case
return Character.toLowerCase(a) > Character.toLowerCase(b);
}
else {
//only a is lower case
return false;
}
}
else if (Character.isLowerCase(b)) {
//only b is lower case
return true;
}
else {
//both are upper case
return Character.toLowerCase(a) > Character.toLowerCase(b);
}
}
else {
//different characters
return Character.toLowerCase(a) > Character.toLowerCase(b);
}
}
}
The output that is generated is:
unsorted: thisIsAString
sorted: AiiIghnrssStt
unsorted: thisIsAStringaAabBs
sorted: aaAAiiIbBghnrsssStt
If you are considering other methods too, from Java 8 you can do it by mixing streams and comparators.
import java.util.*;
import java.util.stream.Collectors;
public class Main {
private static List<Character> order = new ArrayList<>(Arrays.asList('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'H', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z'));
public static void main(String[] args) {
String example = "thisIsAString";
List<Character> cl = example.chars().mapToObj(c -> (char) c).collect(Collectors.toList());
List<Character> ls = cl.stream().sorted(Comparator.comparingInt(order::indexOf)).collect(Collectors.toCollection(ArrayList::new));
StringBuilder result = new StringBuilder();
for (Character c : ls) result.append(c);
System.out.println(result);
}
}

MorseCode class not translating

This program is supposed to translate English into morse code, but every time i input a word I get English letters and numbers such as "\cf0" for hi. I am pretty sure the morse code array has the right values. Could it be a formatting problem? PLease help. thanks.
MorseCode class
public class MorseCode {
public static String decode(char[] alphabet, String[] morseCode, String originalMessage) {
char currentChar;
String getMorseChar;
String convertedString = " ";
for (int i = 0; i < originalMessage.length(); i++) {
convertedString = " ";
currentChar = originalMessage.charAt(i);
getMorseChar = convert(currentChar, alphabet, morseCode);
convertedString = convertedString + getMorseChar;
}
return convertedString;
}
public static String convert (char currentChar, char[] alphabet, String[] morseCode) {
String morse = "";
for (int x = 0; x < alphabet.length; x++) {
if (currentChar == alphabet[x])
morse = morseCode[x];
}
return morse;
}
}
MorseCodeTester class
public class MorseCodeTester {
public static void main(String[] args) throws IOException {
String[] morseCode = new String[26];
char[] alphabet = { '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' };
Scanner scanner = new Scanner(System.in);
Scanner inFile = new Scanner(new File("morse.rtf"));
for (int x = 0; x < 26; x++) {
morseCode[x] = inFile.next( );
}
inFile.close();
System.out.println("What message would you like to translate?");
String originalMessage = scanner.next();
String converted = MorseCode.decode(alphabet, morseCode, originalMessage);
System.out.println(converted);
}
}

How can I have my translator detect the morse code as a string, not a char

Here is my code. I am having an issue. It works just fine but when you convert morse code to english, it only prints out the morse code single digit letters. Can someone give me a solution or at least help me understand what is wrong because it is immensely frustrating.
Here is the bit of my code that matters
An example of the problem is when i put in .- it printed e and t, not a.
public class Project1
{
public static void main( String [] args )
{
System.out.println();
choice();
}
public static void choice()
{
int user_choice = 0;
user_choice = Input.getInt("Enter 1 if you want to change English to Morse code, and enter 2 to change Morse code to English");
if(user_choice == 1)
{
String output = new String();
String inital = new String();
inital = english_to_morse();
for( int k = 0; k < inital.length(); k++)
{
output += morse(inital.charAt( k ));
}
System.out.print(output);
}
if(user_choice == 2)
{
String output2 = new String();
String inital2 = new String();
inital2 = morse_to_english();
for( int k = 0; k < inital2.length(); k++)
{
System.out.println("#####"+String.valueOf(inital2.charAt( k ))+"#####");
output2 += english(String.valueOf(inital2.charAt( k )));
}
System.out.print(output2);
}
}
public static String english_to_morse()
{
String user_input = new String();
user_input = Input.getString("Enter a phrase and I'll convert it to Morse Code");
return user_input.toLowerCase();
}
public static String morse_to_english()
{
String user_input = new String();
user_input = Input.getString("Enter a phrase in Morse Code and I'll convert it to English");
return user_input.toLowerCase();
}
public static String morse(char letter)
{
String output = new String();
char[] alphabet_numbers = {'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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ' };
String morse_code[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "|" };
for( int j = 0; j < alphabet_numbers.length; j++ )
{
if (alphabet_numbers[j]==letter)
{
output = morse_code[j];
}
}
return output + " ";
}
public static String english(String letter)
{
String output = new String();
String alphabet_numbers[] = {"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", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " " };
String morse_code[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "|" };
for( int j = 0; j < morse_code.length; j++ )
{
if (morse_code[j].equals(letter))
{
output = alphabet_numbers[j];
}
}
return output + " ";
}
}
Well the reason why .- is giving et instead of a is due to the way you're reading the string.
Your code reads . and then looks up the table to determine whether it corresponds to any alpha character, in which case it does: e. Then you read a - and you look it up and you get a t.
If your input is literally just
.-.---.-.-.........-----.-.-.-.-
You're pretty much stuck because you don't know when one ends and another begins. As another example, how should one distinguish between the following strings
.
..
...
....
They are all equally valid signals, but depending on how you interpret it, you get very different results.
You can't say something like "I'll just take the longest matching string" because there is no reason why that is a valid rule.
If the sample input I provided above does not match your input, you should indicate what your input is.
The problem is in how you iterate your strings.
When going from English to Morse, it is ok to just iterate single characters as you do here:
for( int k = 0; k < inital.length(); k++) {
output += morse(inital.charAt( k ));
}
but when going from Morse to English you have to iterate several characters at once, because a symbol in Morse generally spans several characters. For instance, the Morse string .- -... -.-. has three symbols that correspond to abc in English, but they have 2, 4 and 4 characters each.
So when iterating your Morse string, you have to split it by spaces, and iterate each of the substrings. In the case above, you'll iterate .-, then -... and then -.-.:
for(String symbol : inital2.split(" ")){
output2 += english(symbol);
}
Your problem is this line
output2 += english(String.valueOf(inital2.charAt( k )));
You give ".-" as input, but it does not convert ".-", because it takes each character of the string ".-" and converts it, which gives your "e t" result.
To fix this you have to use a separator in your morse code input. You already somehow defined " " as a separator so I will use it.
if(user_choice == 2){
String output2 = new String();
String[] inital2 = morse_to_english().split(" ");
for( int k = 0; k < inital2.length; k++){
output2 += english(inital2[k]);
}
System.out.print(output2);
}

Errors that don't exist

Umm. This is awkward but I'm getting some errors that say stuff that is totally untrue.
Could someone give me a suggestion on how to fix it. I'm new to java so simple answers would be the best.
Thanks.
public class Project1
{
public static void main( String [] args )
{
System.out.println();
String output = new String();
String inital = new String();
inital = english_to_morse();
for( int k = 0; k < inital.length(); k++)
{
output += morse(inital.charAt( k ));
}
System.out.print(output);
System.out.println();
}
public static void choice()
{
int user_choice = 0; ///This is the method giving me grief!!!!!!
user_choice = Input.getInt("Enter 1 if you want to change English to Morse code, and enter 2 to change Morse code to English");
if(user_choice == 1)
{
english_to_morse();
}
if(user_choice == 2)
{
morse_to_english();
}
public static String english_to_morse()
{
String user_input = new String();
user_input = Input.getString("Enter a phrase and I'll convert it to Morse Code");
return user_input.toLowerCase();
}
public static String morse_to_english()
{
String user_input = new String();
user_input = Input.getString("Enter a phrase in Morse Code and I'll convert it to English");
return user_input.toLowerCase();
}
public static String morse(char letter)
{
String output = new String();
char[] alphabet_numbers = {'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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ' };
String morse_code[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "-----", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "|" };
for( int j = 0; j < alphabet_numbers.length; j++ )
{
if (alphabet_numbers[j]==letter)
{
output = morse_code[j];
}
}
return output + " ";
}
}
This is the problem:
public static void choice()
{
int user_choice = 0; ///This is the method giving me grief!!!!!!
user_choice = Input.getInt("Enter 1 if you want to change English to Morse code, and enter 2 to change Morse code to English");
if(user_choice == 1)
{
english_to_morse();
}
if(user_choice == 2)
{
morse_to_english();
}
public static String english_to_morse()
You never finish the choice() method - so you can't start the english_to_morse method.
I strongly suspect that the first error message from the compiler was at the start of the english_to_morse method. Once you're source is that broken (trying to declare one method inside another) it shouldn't be a surprise that other error messages may seem strange.
It's a good idea to:
Compile often, and fix problems as soon as they occur. Then if you suddenly get a slew of errors, you know that it can only be due to what you've done very recently.
A huge number of errors is usually due to something like this - look at the first error message, or at least where you start getting a lot of errors, and that can often find the problem.
Getting the IDE to format your code can help you find missing braces too.

Categories