Related
I am trying to remove some special char from my string and replace it with other string, i write this method but it not work fine :
private String nameNormalizer(String nameString) {
char[] LETTERS_TO_REPLACE = new char[]{
'À', 'Á', 'Â', 'Ã', 'Ä', 'Æ',
'È', 'É', 'Ê', 'Ë', '&',
'Ì', 'Í', 'Î', 'Ï',
'Ò', 'Ó', 'Ô', 'Ö', 'Œ',
'Ù', 'Ú', 'Û', 'Ü',
'Ç', 'Č',
'Ñ',
'Š', 'ß',
'Ž'
};
String[] LETTERS_REPLACEMENT = new String[]{ //
"A", "A", "A", "A", "AE", "AE",
"E", "E", "E", "E", "E",
"I", "I", "I", "I",
"O", "O", "O", "OE", "OE",
"U", "U", "U", "UE",
"C", "C",
"N",
"S", "SS",
"Z"
};
char[] surnameArray = nameString.toUpperCase().toCharArray();
int i_s = 0;
int k =0;
int len_s = LETTERS_TO_REPLACE.length;
int len_name = nameString.length();
StringBuilder sb_s = new StringBuilder();
while(k < len_name) {
String b_s = ;
while (i_s < len_s){
if((surnameArray[k] == LETTERS_TO_REPLACE[i_s])) {
b_s =(LETTERS_REPLACEMENT[i_s]);
break;
}
else{
b_s = "" + surnameArray[k];
i_s++;
}
}
sb_s.append(b_s);
k++;
}
String newName = sb_s.toString();
return newName;
}
My method replace only the first occurence and after append the original char element on newName ...
How i can match all char on string and edit it?
this is my first post on this platform ,im kinda new to this java programing and also not that good at english :p
My teacher asked for a morse code translator that does morse to letters and vice versa
Here's the code i came up with:
import java.util.Scanner;
public class Morse2 {
public static void main(String[] args){
String[] letras = { "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"};
String[] MORSE = {
".-" ,"-...","-.-.","-.." ,"." ,
"..-.","--." ,"....",".." ,".---",
"-.-" ,".-..","--" ,"-." ,"---" ,
".--.","--.-",".-." ,"..." ,"-" ,
"..-" ,"...-",".--", "-..-","-.--",
"--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";
frase=frase.toLowerCase();
String[] paraletras=frase.split("");
String[]paraMorse=frase.split(" ");
for(int i=0;i< paraletras.length;i++){
for(int j=0;j< letras.length ;j++){
if (paraletras[i].equals(letras[j])){
resp=resp+ MORSE[j]+" ";}
}
}
for(int k=0;k<paraMorse.length;k++){
for (int l=0;l<MORSE.length;l++){
if(paraMorse[k].equals(MORSE[l])){
resp=resp+letras[l]+ " ";}}
}
System.out.print(resp);}
}
The class compiles fine but im having some issues with my output,more specifically the order of the output:
e.g My input " a b -.- c "
What i wanted ".- -... k -.-."
What i got ".- -... -.-. k"
I believe that's because i used 2 for cycles instead of 1 but i cant really tell how to do it.Would apreciate some help
Also when the user writes an impossible character like "*" im suppossed to put an "?" in that position and im also strugling on that i dont know if i should use a if else cycle or what
Please help me and thank you everybody ^^
Yes you are correct. It is because you run your loops sequentially.
You need one loop over your input, then check if one piece of input is a letter - take translation from letters array, if it is a MORSE take from Morse array.
Actaully arrays are not the best approach. It is much easier to use one Map where letter will be a key, MORSE will be a value.
then code may look like:
public static void main(String... args) {
String[] letras = { "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" };
String[] MORSE = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Map<String, String> decodeMap = new HashMap<String, String>();
for (int i=0; i< letras.length; i++)
{
decodeMap.put(letras[i], MORSE[i]);
}
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp = "";
frase = frase.toLowerCase();
String[] paraletras = frase.split(" ");
for (int i = 0; i < paraletras.length; i++) {
boolean gotValue = false;
for (Entry<String, String> decodeEntry: decodeMap.entrySet()) {
if (decodeEntry.getKey().equals(paraletras[i]))
{
// it is a letter print its MORSE
resp += decodeEntry.getValue();
gotValue = true;
break;
} else if (decodeEntry.getValue().equals(paraletras[i]))
{
// it is a MORSE - print its letter
resp += decodeEntry.getKey();
gotValue = true;
break;
}
}
if (gotValue)
{
resp += " ";
}
}
System.out.print(resp);
}
You have to evaluate every group or chars to guess if it is morse or not.
Example:
First group: 'a'
is morse -> no
is a letter -> yes -> then convert to morse
Second group: 'b'
is morse -> no
is a letter -> yes -> then convert to morse
Third group: '-.-'
is morse -> yes -> then convert to letter
This code could be more efficient, but I think it is easy to understand. I hope this help you to improve your programming skills.
import java.util.Scanner;
public class Morse2 {
public static void main(String[] args) {
String[] LETRAS = {
"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" };
String[] MORSE = {
".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-",
"-.--", "--.." };
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp = "";
frase = frase.trim().toLowerCase();
String[] chars = frase.split(" ");
for (int i = 0; i < chars.length; i++) {
String group = chars[i];
String newChar = null;
for (int j = 0; j < LETRAS.length; j++) {
if (LETRAS[j].equals(group)) {
newChar = MORSE[j];
break;
}
}
if (newChar == null) {
for (int j = 0; j < MORSE.length; j++) {
if (MORSE[j].equals(group)) {
newChar = LETRAS[j];
break;
}
}
}
if (newChar == null) {
System.out.println("Group not found: "+group);
continue;
}
resp += newChar + " ";
}
System.out.print(resp);
in.close();
}
}
Sorry to be such a noob,but probably is also because ive been here since 8 hours ago but why is this code giving me only the morse code to the letter 'a' a couple times?
import java.util.Scanner;
public class Morse2 {
public static void main(String[] args){
String[] abecedario = { "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"};
String[] MORSE = {
".-" ,"-...","-.-.","-.." ,"." ,
"..-.","--." ,"....",".." ,".---",
"-.-" ,".-..","--" ,"-." ,"---" ,
".--.","--.-",".-." ,"..." ,"-" ,
"..-" ,"...-",".--", "-..-","-.--",
"--.."};
System.out.println("Insira uma frase em codigo morse para uma traducao para texto ou vice-versa");
Scanner in=new Scanner(System.in);
String frase =in.nextLine();
String resp="";
frase=frase.toLowerCase();
String[] palavra=frase.split(" ");
for(int i=0;i< palavra.length;i++){
String letra=palavra[i];
String novochar="";
for (int j=0;j<abecedario.length;j++){
if (abecedario[j].equals(letra));
novochar=MORSE[j];
break;
}
if(novochar==""){
for (int j=0;j<MORSE.length;j++){
if (MORSE[j].equals(letra));
novochar=abecedario[j];
break;
}
}
if(novochar==""){
novochar="?";
continue;
}
resp=resp+novochar+" ";
}
System.out.println(resp);
}
}
I'm not sure at all how to go about this, but I want to generate 1000 randomly generated 7 digit numbers, and 5 letter names. The names could be like "FjwaS" anything, it doesnt have to be an actual name. I want to store all these values in 2 different arrays. telephone array, then a name array. I'm not sure how I should approach this at all.
Easy:
1 - create your collection
2 - iterate 1000 times
..2a - generate random values
..2b - populate your collection
Below is the code for a very basic implementation for the problem given above. Later, you can use your desired collection. Change the value of MAX to your desired length. The main work is done by the randomInt() and randomString() functions.
import java.util.*;
public class RandomDirectoryCreation
{
static final String alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args)
{
final int MAX = 10;
String[] name = new String[MAX];
int[] telephone = new int[MAX];
for(int i=0; i<MAX; i++)
{
name[i] = randomString(5);
telephone[i] = randomInt(1000000, 9999999);
}
for(int i=0; i<MAX; i++)
{
System.out.println("Name: " + name[i] + " Telephone: " + telephone[i]);
}
}
public static int randomInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static String randomString(int len)
{
Random rand = new Random();
StringBuilder word = new StringBuilder(len);
for( int i = 0; i < len; i++) {
word.append( alphabets.charAt(rand.nextInt(alphabets.length())));
}
return word.toString();
}
}
Sample Output:
Name: kBbSL Telephone: 4152479
Name: GOEat Telephone: 7473373
Name: KRBPq Telephone: 8346073
Name: yqjpu Telephone: 7553636
Name: yvRBA Telephone: 2133757
Name: ajUBg Telephone: 3826625
Name: BhBVr Telephone: 5714195
Name: AvNYB Telephone: 6179815
Name: DfsxM Telephone: 6611458
Name: gJRka Telephone: 2114751
References:
How do I generate random integers within a specific range in Java?
How to generate a random alpha-numeric string?
Why reinvent the wheel? You can use RandomStringUtils from Apache Commons.
import org.apache.commons.lang3.RandomStringUtils;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] names = new String[1000];
String[] telephones = new String[1000];
for (int i=0; i<1000; i++) {
String randomName = RandomStringUtils.randomAlphabetic(5);
names[i] = randomName;
String randomTelephone = RandomStringUtils.randomNumeric(7);
telephones[i] = randomTelephone;
}
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(telephones));
}
}
I had written it to generate a random string, you may change it according to your needs:
import java.util.Random;
public class randomWord
{
public static void main(String args[])
{
Random charp = new Random();
String[] chars = {"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", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "M", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "!", "#", "#", "$", "%", "^", "&", "*", "(", ")", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
String[] word = new String[9];
for(int i = 0; i < 9;i++)
{
word[i] = chars[charp.nextInt(70)];
}
System.out.print("Your randomly generated string is: ");
for(int i = 0; i < 9;i++)
{
System.out.print(word[i]);
}
Random number = new Random();
System.out.println("\nRandom number: "+number.nextInt(6));
}
}
I have the following string array:
String arry[] = { "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", "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", "`", "~", "!", "#", "#", "$", "%", "^",
"&", "*", "(", ")", "-", "_", "=", "+", ";", ":", "'", "|", "",
"<", ",", ">", ".", "/", "?", };
In this String array how to get a values randomly ?
For example:
AG.4fF
h9_wO4
So far, I have the following code:
for (String st : arry) {
String randomValue = arry[new Random().nextInt(arry.length)];
System.out.println(" Inside array values :-->> " + randomValue);
}
For this code, it returns all the array values, then how to form a multiple combinations.
as i mentioned earlier?
Do you mean generating random string from this set of characters? You can perform it in this way:
int len = ...; // length of resulting string
StringBuilder builder = new StringBuilder();
Random rand = new Random();
for (int i = 0; i < len; ++i) {
String c = arry[rand.nextInt() % arry.length];
builder.append(c);
}
String str = builder.toString();
To get a String of characters you can do
static final String chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
"abcdefghijklmnopqrstuvwxyz" +
"0123456789`~!##$%^&*()-_" +
"=+;:'|\"<,>./?";
static final Random rand = new Random();
public static String randString(int length) {
char[] gen = new char[length];
for (int i = 0; i < length; i++)
gen[i] = chars.charAt(rand.nextInt(chars.length));
return new String(gen);
}
import java.util.Random;
...
Random random = new Random(); // Step 1 - creating random object
System.out.println(arry[random.nextInt(arry.length)]); // Step 2
In step 2. we generate random number within range of 0 to arrays length than get element reside
Random.nextInt(int n) method returns pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)
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);
}