Related
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 am writing a program to check wether the given sentence is a panagram or not, but I am not able to compare each character with the characters in a string.
Can anyone suggest me a method to get the desired output?
Scanner scan = new Scanner(System.in);
String panagram = scan.nextLine();
String word = panagram.toLowerCase();
System.out.println(word);
String a[] = { "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" };
int count = 1;
System.out.println("a=" + a.length);
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < word.length(); j++) {
if ((a[i]).equals(word.charAt(j)))// problem occurs here {
count++;
break;
}
}
}
if (count == 26) {
System.out.println("pangram");
} else {
System.out.println("not pangram");
}
You can use:
(a[i]).equals(String.valueOf(word.charAt(j)))
or change your a array from String[] to char[] and compare the character using the == operator.
You can convert it to a String and then compare it.
String s = Character.toString('c');
if(s.equals(s2)){..}
Or you could make it a String by adding it to an empty string.
String s = 'c' + "";
if(s.equals(s2)){..}
Or you could compare it's ascii value.
As there are only single characters, why don't you use a character array.
char []a = {'a', 'b', 'c'....};
if(a[i] == 'a')//you could use == in this case.
{..}
Also you don't need to check it that way.
You could create a boolean array of 26 size, as there are only 26 characters and check if every character is present atleast once or not
boolean []arr = new boolean[26];
for(int i = 0; i < word.length(); ++i)
{
arr[word.charAt(i) - 'a'] = true;
}
isPan(arr);
public boolean isPan(boolean[] arr)
{
for(int i = 0; i < arr.length; ++i)
if(!arr[i])
return false;
return true;
}
A simple O(n) solution.
Or you could use a Set and check it's size.
HashSet<Character> set = new HashSet();
for(int i = 0; i < word.length(); ++i)
set.add(word.charAt(i));
System.out.println(set.size() == 26 ? "Pangram" : "Not Pangram");
//A 2 liner would be
HashSet<Character> set = new HashSet<Character>(Arrays.asList(word.toCharArray()));
System.out.println(set.size() == 26 ? "Pangram" : "Not Pangram");
A point added by spookieCookie. These approaches apply only when the string has only lower case alphabets.
String s = "sdgosdgoih3208ABDDu23pouqwpofjew##$%^&".repalceAll("[^A-Za-z]+", "");
String s = s.toLowerCase();
//do the computation then
Convert the array into an arraylist
List<Character> alphabet = Arrays.asList(a);
Make a list to hold the characters that are read:
Set<Character> chars = new HashSet<>();
Then check whether every character in the sentence is part of the alphabet. Duplicates are not added due to the characteristics of Set
for (Character c : word.toCharArray()) {
chars.add(c);
}
Then check whether the size of the Set is equal to the given alphabet:
return (chars.size() == alphabet.size());
Try this instead:
public void checkPanagram() {
boolean isPanagram = false;
String word = "The quick brown fox jumps over the lazy dog";
String a[] = { "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" };
for (int i = 0; i < a.length; i++) {
if (word.toLowerCase().contains(a[i])) {
isPanagram = true;
} else {
isPanagram = false;
break;
}
}
if (isPanagram) System.out.println("Yes, panagram");
else System.out.println("No, not panagram");
}
You can use String.contains(String) as every letter in a already is a String.
for (int i = 0; i < a.length; i++) {
if (word.contains(a[i])) {
count++;
// } else { break;
}
}
A remark: better use String[] a which is a more regular syntax instead of String a[] whose Syntax was added for C/C++ compatibility.
To check equality of a string with a char you could change your code minimally
if ((a[i]).equals(word.charAt(j)) to if ((a[i]).equals("" + word.charAt(j))
This gives you an equality check between two strings.
Alternatively you can change the line if ((a[i]).equals(word.charAt(j))
to if ((a[i]).equals(word.substring(j,j+1))
I want to create method thath generate numbering for Database record in the future.
My rules like this :
[start] - [end]
0001-
9999
A001-
A999
AA01-
AA99
AB01-
AB99
AC01-
AC99
etc...
......
......
ZZZZ
Its look similar using Excel column numbering.
How to create like that, using Java?
Here is my code :
But i confuse in how to check if in the last number like 9999 , A999 etc
public static void main(String [] args) {
String lastSchCode = "9999";
System.out.println(generateSchCode(lastSchCode));
}
public static String generateNextNum(String number) {
int nextNum = Integer.parseInt(number);
String padNextNum = lPadZero(nextNum+1, 4);
return padNextNum;
}
public static String generateSchCode(String lastSchCode) {
String nextSchCode = null;
String [] alphabets = {"A", "B", "C", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
int counter = 0;
for (int i = 0; i < lastSchCode.length(); i++) {
if (lastSchCode.charAt(i) == '9') {
counter++;
}
}
if (generateNextNum(lastSchCode).equals("10000")) {
int num = 9999;
} else {
}
return nextSchCode;
}
Please help. Thank you.
Have a look at this snippet. You have to convert the number based on radix 36.
int[] ints = { 0, 1, 10, 35, 36, 46, 36*36-1, 36*36*36-1, 36*36*36*36-1};
for (int i : ints) {
System.out.printf("int: %7d string: %4s%n", i, Integer.toString(i, 36));
}
output
int: 0 string: 0
int: 1 string: 1
int: 10 string: a
int: 35 string: z
int: 36 string: 10
int: 46 string: 1a
int: 1295 string: zz
int: 46655 string: zzz
int: 1679615 string: zzzz
public static void main(String [] args) {
String lastSchCode = "9999";
System.out.println(generateSchCode(lastSchCode));
}
public static String generateNextNum(String number) {
int nextNum = Integer.parseInt(number);
String padNextNum = lPadZero(nextNum+1, 4);
return padNextNum;
}
public static String generateSchCode(String lastSchCode) {
String nextSchCode = null;
String [] alphabets = {"0","1","2","3","4","5","6","7","8","9","A", "B", "C", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
List<String> alphabetsAsList = Arrays.asList(alphabets);
int counter = 0;
for (int i = lastSchCode.length(); i > 0; --i) {
if(lastSchCode.charAt(i) == '9'){
incrementWith9(lastSchCode,i);
}
else{
String s = lastSchCode.substring(index,index+1);
String incrementedString = alphabetsAsList.get(alphabetsAsList.indexOf(s) + 1);
char[] charArr = lastSchCode.toCharArray();
charArr[index] = incrementedString.charAt(0);
nextSchCode = charArr.toString();
}
}
return nextSchCode ;
}
public String incrementWith9(String input, int index){
char[] ca = input.toCharArray();
ca[index] = '0';
if( index != 0 && input.charAt(index -1 ) == '9'){
incrementWith9(ca.toString(),index -1);
}
elseif(index == 0 ){
return "A000";
}
else{
String [] alphabets = {"0","1","2","3","4","5","6","7","8","9","A", "B", "C", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
List<String> alphabetsAsList = Arrays.asList(alphabets);
String s = input.substring(i,i+1);
String incrementedString = alphabetsAsList.get(alphabetsAsList.indexOf(s) + 1);
char[] charArr = input.toCharArray();
charArr[i] = incrementedString.charAt(0);
nextSchCode = charArr.toString();
}
return nextSchCode;
}
This should work. Or atleast you get the idea right.. ;)
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)
I'm trying to check if my input is a consonant. However it tells me at the line below that they are incompatible types (boolean vs String)
if (medeklinkerGeraden = medeklinkers [r]) {
^
public String medeklinkerRaden () {
String medeklinkerGeraden = "";
boolean bevatMedeklinker = false;
System.out.println("U mag een medeklinker gokken!");
medeklinkerGeraden = Input.readString();
String [] medeklinkers = {"b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"};
do {
for (int r = 0; r < medeklinkers.length; r++)
if (medeklinkerGeraden = medeklinkers [r]) {
bevatMedeklinker = true;
}
}
while (! bevatMedeklinker);
return medeklinkerGeraden;
}
Refactor like this:
if (medeklinkers[r].equals(medeklinkerGeraden)) {
bevatMedeklinker = true;
}
You must use == instead of =
if (medeklinkerGeraden == medeklinkers [r])