In: Computer Science
: This exercise will give you a review of Strings and String processing. Create a class called MyString that has one String called word as its attribute and the following methods: Constructor that accepts a String argument and sets the attribute. Method permute that returns a permuted version of word. For this method, exchange random pairs of letters in the String. To get a good permutation, if the length of the String is n, then perform 2n swaps. Use this in an application called Jumble that prompts the user for a word and the required number of jumbled versions and prints the jumbled words. For example, Enter the word: mixed Enter the number of jumbled versions required: 10 xdmei eidmx miexd emdxi idexm demix xdemi ixdme eximd xemdi xdeim Notes: 1. It is tricky to swap two characters in a String. One way to accomplish this is to convert your String into an array of characters, swapping the characters in the array, converting it back to a String and returning it. char[] chars = word.toCharArray(); will convert a String word to a char array chars. String result = new String(chars); converts a char array chars into a String. p 6 2. Use Math.random to generate random numbers. (int)(n*Math.random()) generates a random number between 0 and n-1. java
JAVA CODE: (MyString.java)
import java.util.*;
public class MyString
{
//variable to store the word
String word;
// constructor to initialize the object
public MyString(String word)
{
this.word=word;
}
// method to return a permuted word
public String permute()
{
// converting word into character
array
char[] chars =
word.toCharArray();
// finding the length of the
word
int n=word.length();
// swapping characters for 2 * n
times
for(int i=0;i< 2*n;i++)
{
// finding two
random numbers
int
r1=(int)(n*Math.random());
int
r2=(int)(n*Math.random());
//swapping the
characters at position r1 and r2 of the array
char
t=chars[r1];
chars[r1]=chars[r2];
chars[r2]=t;
}
//converting character array into
string
String result = new
String(chars);
// return the string
return result;
}
}
JAVA CODE (Jumble.java)
import java.util.*;
public class Jumble
{
public static void main(String args[])
{
//creating scanner object to get
keyboard input
Scanner kb=new
Scanner(System.in);
//getting the word from the
user
System.out.print("Enter the word:
");
String word=kb.next();
// getting the n value
System.out.print("\nEnter the
number of jumbled versions required: ");
int n=kb.nextInt();
System.out.println();
// calling the permute() method for
n times
for(int i=0;i<n;i++)
{
MyString ob=new
MyString(word);
System.out.println(ob.permute());
}
}
}
SCREENSHOT FOR OUTPUT: