1
I intend to generate a randomized, scrambled word from a vector. It’s already generating a random word, but it’s not scrambled. I created a method called Scramble where the words will be shuffled but I don’t know I can call on Main.
Current code:
import java.util.Random;
import java.util.Scanner;
public class findthewordgame {
public static void arrayword () {
String[] wordgame = new String[5];
wordgame[0] = "TEA";
wordgame[1]= "COFFE";
wordgame[2]= "BOAT";
wordgame[3]="SEA";
wordgame[4]="SUN";
int idx = new Random().nextInt(wordgame.length);
String random = (wordgame[idx]);
System.out.println(wordgame[idx]);
}
public static String scramble(Random random, String inputString )
{
// Convert your string into a simple char array:
char a[] = inputString.toCharArray();
// Scramble the letters using the standard Fisher-Yates shuffle,
for( int i=0 ; i<a.length ; i++ )
{
int j = random.nextInt(a.length);
// Swap letters
char temp = a[i]; a[i] = a[j]; a[j] = temp;
}
return new String( a );
}
public static void main (String[] args){
arrayword();
}
}
String[] wordgame = {"TEA", "COFFE", "BOAT", "SEA", "SUN"};
- Simpler yet.– Victor Stafusa
And would already take advantage and tidy up code style details, such as more or less spaces, variable names and use
char[] a
instead ofchar a[]
.– Victor Stafusa
@Victorstafusa Yes I agree and I appreciate the comments. This last one from
char a[]
I didn’t even notice!– Isac
I did as suggested is working and is not. appears the word twice once correctly written and in the same line again but scrambled. i intend that the word generates only once and only shuffled. it has to help sff?
– Diana Madeira
Just comment System.out.println(palavraEscolhida); and already giving.
– Diana Madeira
@Dianamadeira take into account that the algorithm you are using to shuffle (which I did not change on purpose) does not guarantee 100% that the word battled will be different from the original, although it is very likely. If you imagine a word with 3 letters that changes: 1-3, 2-2 and 3-1, it is the same as the original. For that not to happen would have to use another algorithm, or using the same continue to shuffle the same word until different.
– Isac