-2

I'm trying to make an Anagram puzzle where I input a word (for example, fire) and it scrambles it randomly around for me (and it ends up like "rfie", "frei", etc...) Below is the basics of what I'm trying to do. All I need to know is how to scramble the string.

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Input word");
        String Word = sc.nextLine();
     
        //Program jumbles word here
     
        System.out.println(Word);
        //Jumbled word is printed one previous line
    }
  • Have a go yourself first. You might surprise yourself and manage it without help! Btw the convention in Java is for local variables to begin with a lowercase letter. Classes begin with an uppercase. If you follow this convention it helps to distinguish between the two. – Ben Thurley Mar 02 '15 at 13:58

1 Answers1

0

You could use the following algorithm:

public static void main(String[] args){

    String myWord = "Hello";
    StringBuilder jumbledWord = new StringBuilder();
        jumbledWord.append(myWord);
        Random rand = new Random();
        for (int i = myWord.length(); i > 0; i--)
        {
             int index1 = (rand.nextInt(i+1) % myWord.length());
             int index2 = (rand.nextInt(i) % myWord.length());

             char temp = jumbledWord.charAt(index1);
             jumbledWord.setCharAt(index1, jumbledWord.charAt(index2));
             jumbledWord.setCharAt(index2, temp);

         }

         System.out.println(jumbledWord);
}
Tachyon
  • 452
  • 7
  • 19