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)
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);
}
}
public class MorseCodeTranslator {
public static void main(String[] args) {
String [] letter = {"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 = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", ".----", "..---", "...--", "....-", ".....", "-....", "--...", "---..", "----.", "-----"};
System.out.println("Enter in some words or letter to convert them to morse code : ");
Scanner keyboard = new Scanner(System.in);
String english = keyboard.nextLine();
System.out.println(english.toLowerCase());
for(int i = 0; i < english.length(); i++){
char test = english.charAt(i);
for (int j = 0; j < letter.length(); j++){
if(letter.charAt(j) == test){
System.out.print(morse[j]);
}
}
}
/*** SAMPLE INPUT/OUTPUT
*
* Please enter some text: Hello World
* Morse Code: .... . .-.. .-.. --- .-- --- .-. .-.. -..
*/
}
I need to convert English letters that the user inputs into Morse code. I want it to take the length of letter[] and compare it to the indexes of morse[], then to print out the Morse code counterpart. But I get an error at "letter.length();" saying "cannot find symbol- method length()". It works where "english.length();" is. Is there another way to do this with Arrays?
On arrays, length is a property, so you just say letter.length. On a String, it is a method, so there you say english.length().
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'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));
}
}