I wanna write a program in which different letters of a String Array form different words based on random orders. The most important part is that letters should not be duplicate in one word. I could somehow make the correct pattern but the problem is that I can only show them on console and couldn't find a way to save them as a String (like "OMAN"). Here is my code :
int size = 4;
ArrayList<Integer> list = new ArrayList<Integer>(size);
Random rnd = new Random();
while (list.size()<size) {
int random = rnd.nextInt(size);
if (!list.contains(random)) {
list.add(random);
}
}
String[] words = {"M","O","A","N"};
for(int i=0 ; i<size ; i++){
System.out.println(words[list.get(i)]);
}
You could accumulate them to a StringBuilder:
StringBuilder sb = new StringBuilder(size);
for(int i = 0 ; i < size ; i++) {
sb.append(words[list.get(i)]);
}
String result = sb.toString();
First declare a blank string
String answer = "";
Then in your for loop do
answer+=words[list.get(i)];
When you leave the for loop
System.out.println(answer);
Will have what you want. To do it more efficiently I'd read up on StringBuilder.
You can do something like this,
int size = 4;
ArrayList<Integer> list = new ArrayList<Integer>(size);
Random rnd = new Random();
while (list.size() < size) {
int random = rnd.nextInt(size);
if (!list.contains(random)) {
list.add(random);
}
}
String[] words = {"M", "O", "A", "N"};
String finalWord = "";
for (int i = 0; i < size; i++) {
finalWord += words[list.get(i)];
}
System.out.println(finalWord);
Related
Im working on an assignment for school where i am going to finish a short password generator.
when trying to loop adding characters out of the string, it ends up adding the same character, but if i would just print out characters it gives different ones. could someone explain why this is? i would really like to learn.
private void program() {
System.out.println(generate(all));
}
Random rand = new Random();
String all = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int randomInt = rand.nextInt(all.length());
char randomchar = all.charAt(randomInt);
StringBuilder sb = new StringBuilder();
String generate (String string) {
while (sb.length() < 10) {
sb.append(randomchar);
}
return sb.toString();
}
}
You are setting nextInt and nextChar gloabally. This need to be moved to your generation method.
String generate (String string) {
StringBuilder sb = new StringBuilder();
while (sb.length() < 10) {
int randomInt = rand.nextInt(all.length());
char randomchar = all.charAt(randomInt);
sb.append(randomchar);
}
return sb.toString();
}
Size your StringBuilder for efficiency (and big passwords)
public String generatePassword(String candidateChars, int passwordLength) {
Random rand = new Random();
int max = candidateChars.length();
StringBuilder sb = new StringBuilder(passwordLength);
for (int i = 0; i < passwordLength; i++) {
char randomchar = candidateChars.charAt(rand.nextInt(max));
sb.append(randomchar);
}
return sb.toString();
}
You should (re-)generate randomInt as well as randomchar within loop:
while (sb.length() < 10) {
// we want fresh value on ach itteration
int randomInt = rand.nextInt(all.length());
char randomchar = all.charAt(randomInt);
sb.append(randomchar);
}
//Please, help me to fix this codes. I wanna return a String that the have same chars with the sending String but is in different order.
public static String mix(String s){
int random;
int n= s.length();
int [] control = new int[n];
String miX="";
for(int i=0 ; i < n ; i++){
random = (int)(1+Math.random()*(n));
if( control[i] != random ){
control[i]= random;
miX += s.charAt(random);
}
}
return miX;
}
You can make use of Collections.shuffle.
String word= "word";
ArrayList<Character> chars =newArrayList<Character>(word.length());
for(char c : word.toCharArray()){
chars.add(c); }
Collections.shuffle(chars);
char[] shuffled =newchar[chars.size()];
for(int i =0; i < shuffled.length; i++){
shuffled[i]= chars.get(i);
}
String shuffledWord =newString(shuffled);
Another way similar to your code without using functions is:
public static void main(String[] args) {
// Create a random object
Random r = new Random();
String word = "Animals";
System.out.println("Before: " + word );
word = scramble( r, word );
System.out.println("After : " + word );
}
public static String scramble( Random random, String inputString )
{
// Convert your string into a simple char array:
char a[] = inputString.toCharArray();
// Scramble the letters
for( int i=0 ; i<a.length-1 ; i++ )
{
int j = random.nextInt(a.length-1);
// Swap letters
char temp = a[i]; a[i] = a[j]; a[j] = temp;
}
return new String( a );
}
You should select two positions within the length of the String RANDOMLY and then exchange them .
Run this within a loop for any number of times depending on the amount of randomness you want in your String.
Based on your code you might miss some of the characters in your new string if random selects the same index twice
Mix string chars with this code
import java.util.*;
class MixStringChars
{
public static String mix(String s)
{
StringBuilder sb = new StringBuilder(s);
Random r = new Random();
for (int i = 0; i < s.length(); i++)
{
char curr = sb.charAt(i); //current char
int rix = r.nextInt(s.length()); //random index
char temp = sb.charAt(rix); //memorize char at index rix
sb.setCharAt(rix, curr); //put current char to rix index
sb.setCharAt(i , temp); //put memorized char to i index
}
return sb.toString();
}
public static void main (String[] args)
{
System.out.println(mix("Hello"));
}
}
I am trying to populate a java string array with a variable. the variable contains values which I am reading in from a text file. every time a new value is stored in the array the current value is replaced by the new value.
the code below is what i have tried so far.
int n = 0;
String var1 = value;
String array[] = {var1};
String [] array = new String[n];
for (int i =0; i < n; i++) {
array[n++] = value;
}
Java has only fixed sized arrays; dynamically growing "arrays" are realized with List:
List<String> array = new ArrayList<>();
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array.add(s);
}
for (String t : array) {
System.out.println(t);
}
String seven = array.get(7);
int n = array.size();
if (array.isEmpty()) { ... }
// In Java 8:
array.stream().sorted().forEach(System.out::println);
Using (fixed sized) arrays would be cumbersome:
String[] array = new String[];
String[] otherVar = array;
for (int i = 0; i < 42; ++i) {
String s = "" + i;
array = Arrays.copyOf(array, i + 1);
array[i] = s;
}
Here on every step a new array is created, the content of the old array copied.
Also notice that otherVar keeps the initial empty array.
Note that String[] a is the same as String a[]. The latter is only for compatibility to C/C++, and is less readable.
This will add a string indefinitely. When you read all the data from file you have to set isFileNotEnded = false
boolean isFileNotEnded = true;
List<String> array = new ArrayList<>;
while (isFileNotEnded) {
array.add("hello");
//stop here the infinite loop
}
There are 2 arrays. code[] and text[]
code[0] = 0, text[0] = "Monkey333banana" // has numbers in text
code[1] = 100, text[1] = "Dog"
code[2] = 200, text[2] = "Cat117" // has numbers in text
code[3] = 300, text[3] = "Pig"
I want pick up the array in text[] consisted only alphabet. No numbers.
code[1] = 100, text[1] = "Dog"
code[3] = 300, text[3] = "Pig"
And I want to save another new array.
newCode[0] = 100, text[0] = "Dog"
newCode[1] = 300, newText[1] = "Pig"
Example code :
String[] code = new String[4];
int[] text = new int[4];
code[0] = 0;
code[1] = 100;
code[2] = 200;
code[3] = 300;
text[0] = "Monkey333banana";
text[1] = "Dog";
text[2] = "Cat117";
text[3] = "Pig";
// *** MAGIC **** //
// *** MAGIC **** //
// *** MAGIC **** //
for (int i=0; i<(proper size); i++)
System.out.println(newCode[i]+" : "+newText[i]);
result :
100 : Dog;
300 : Pig;
How can I do this magic? Please help me. Thank you!
Sorry ... for act imprudently, I wrote magic maybe people think this is bad, sorry...
I hope this helps provided:
size of both the arrays are same...
public static void main (String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>(); // store code[] value
ArrayList<String> listS = new ArrayList<String>(); // store string w/o numbers
int code[] = {0, 100, 200, 300}; //example
String text[] = {"M12", "Dog", "117Cat", "Pig"}; //example
for (int i = 0; i < text.length; i++) {
if (! text[i].matches(".*\\d+.*")) { // VERY IMP REGEX TO TEST IF STRING CONTAINS ANY NUMBER
list.add(i); // or add(code[i]);
listS.add(text[i]);
}
}
int newCode[] = new int[list.size()];
int idx = 0;
for (int x : list) {
newCode[idx++] = x;
}
String newText[] = listS.toArray(new String[list.size()]);
for (int i=0; i < newCode.length; i++) {
System.out.println(newCode[i] + " : " + newText[i]);
}
}
Instead of writing magic put some effort/research before posting question
String[] newText = new String[4];
int[] newCode = new int[4];
int j=0;
for(int i=0;i<text.length;++i){
if(text[i].matches("\\A[a-zA-Z]+\\z")){
newCode[j]=code[i];
newText[j++]=text[i];
}
}
for (int i=0; i<j; i++)
System.out.println(newCode[i]+" : "+newText[i]);
That magic:
for(int i=0;i<text.length;i++)
textvalid[i]=true; //saying that all the strings are valid. We will mark them as unvalid later
k=0; //a counter
for(int i=0;i<text.length;i++) { //every string in the array
for(int j=0, char[] text1 = text.toCharArray();j<text1.length;j++) //every character in the string. text1 is the char[] equivallent of text[i]
if(text1[j]<'A' || (text1[j] >'Z' && text1[j]<'a') || text1[j] <='z') //if it is not a capital letter nor a lowercase one
textvalid[i] = false; //mark it as a npn-valid string
if(textvalid[i]==true){ //if it is valid, add it to the newtext array
newText[k++] = text[i];
newCode[k] = code[i];
}
}
Hope it helps. :)
here i am posting a hint further it is your duty to do it yourself
for(char i = 'a'; i <= 'z'; i++){
System.out.println(i+" ");
}
I have a large stringbuffer which i would like to break into smaller parts. The string buffer looks like this
"name1+name2+name3+name4+..........+name2000"
Where
name1=john
name2=prince
and so on.
(You get the idea.name1,name2,name3 stand for actual names of varying length)
Now i would like to store the names in a string array with each positon containing a 200 names.
string[0]="name1+name2+name3+........+name200";
string[1]="name201+name202+...."
How would i go about achieving this task?
StringTokenizer str = new StringTokenizer(<StringBufferObject>);
int count = 0;
int arrCount = 0;
StringBuffer temp;
String[] stringArr = new String[x];
while(str.hasMoreTokens()) {
count++;
if(count != 200) {
temp.append(str.nextToken());
}
else {
stringArr[arrCount] = temp;
temp.delete(0,temp.length());
count = 0;
arrCount++;
}
It would be a lot easier to split a String using String.split() if that's possible:
/* something like this */
String arrayOfStrings = inputString.split("\+");
If you have to keep it as a StringBuffer you'll have to loop over the input and tokenize it yourself.
I guess it would look something like this:
public String[] getTwoHundredStrings(StringBuffer inputBuff, String someToken)
{
String [] nameArray = new String [200];
int currentPos = 0;
int nextPos = 0;
for ( int i = 0; i < 200; i ++ ) {
nextPos = inputBuff.indexOf(someToken, currentPos);
if ( nextPos < 0 ) {
break;
}
String nextName = inputBuff.substring(currentPos, nextPos);
nameArray[i] = nextName;
currentPos = nextPos;
}
/* do some cleanup if nameArray has less than 200 elements */
return nameArray;
You must have some delimiter between each name. To break the string we should have some delimiter.
If you have delimiter you can use subString() in for loop.
try to use
String[] tempNames = new String(namesBuffer).split("+");
and then
int length = (tempNames.length / 200)+ (tempName.length % 200)
String[] names = new String[length];
for(int i = 0 ; i< tempNames.length ; i++){
for(int j = 0 ; j < length ; j++)
names[j] = tempNames[i];
}
hope this helps
Split on "+", using String.split("\\+")
Get chucks, in smaller arrays, Arrays.copyOfRange(...)
Join using Guava Joiner like Joiner.on("+").join(smallerArray)