In: Computer Science
using java with proper header and comments:
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
import java.io.*;
import java.lang.*;
import java.util.Scanner; // Import the Scanner class
import java.lang.Math;
class MyString
{
String word;
//constructor accepting a string vaiable
public MyString(Sting s) {
word=s; // setting the attribute
}
String permute( String str, int i, int j)
{
char ch[] = str.toCharArray(); //converting to string into char Array
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
String result = new String(ch); //converting to char Array into String
return result;
}
}// End of class MyString
Public class Jumble
{
public static void main(String args[])
{
Scanner ss = new Scanner(System.in);
System.out.println("Enter the word");
String p = ss.nextLine(); // Read user input
System.out.println("Enter the number of jumbled versions");
int n = ss.next(); // Read user input
MyString m= new MyString (p);
System.out.println(permute(p, (int)(Math.random() * n), p.length() - 2));
System.out.println(permute(p, (int)(Math.random() * n), p.length() - 1));
}
}