JAVA - Generate a random & scrambled word

1

I want to generate a random and scrambled word from a vector. At the moment it is already generating a random but not scrambled word. I created a method called scramble where the words will be shuffled but I do not know I am not able to call on the 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();


    }
}
    
asked by anonymous 22.09.2017 / 20:39

1 answer

2

To make it work just call the scramble method, which is not being called. You could do it with:

public static void arrayword () {

   ...
   System.out.println(scramble(new Random(), random));
}

And although it is already working, it is not very good because another object Random is being created when a previous one was already created.

We can review this and other code details and turn it into:

//objeto que gera os aleatorios agora é sempre o mesmo e apenas criado uma vez
static Random aleatorio = new Random();

public static void arrayWord () { //agora o nome em camel case

    String[] wordgame = { //inicialização do array mais simples assim
        "TEA",
        "COFFEE",
        "BOAT",
        "SEA",
        "SUN"
    };

    int idx = aleatorio.nextInt(wordgame.length);
    String palavraEscolhida = (wordgame[idx]);

    System.out.println(palavraEscolhida); //escrever a variavel anterior, a escolhida
    System.out.println(scramble(palavraEscolhida));
}

//agora não recebe o aleatorio, usa o mesmo da classe
public static String scramble(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 = aleatorio.nextInt(a.length);

        //Mais legível assim linha a linha
        char temp = a[i]; 
        a[i] = a[j];  
        a[j] = temp;
    }       

    return new String(a);
}

Example working on Ideone

    
22.09.2017 / 21:12