In: Computer Science
Assignment Purpose
Write a well commented java program that demonstrates the use and re-use of methods with input validation.
Instructions
“I dn'ot gvie a dman for a man taht can olny sepll a wrod one way.” (Mrak Taiwn)
“We aer all moratls, Hamrbee is an immoratl, and tehre is no question abuot it.” (Kevin Unknown)
Hint: First generate two random integers in range of the length of the string. Then use substring method to access characters at those locations. Rest is left to your imagination.
Submission
A .java and a .html (generated with Javadoc) file
import java.util.Random;
import java.util.Scanner;
public class A {
/**
* Returns a scramble string.
* The string argument is the string which user wants to scramble.
* <p>
* @param str string to be scrambled
* @return the scrambled string
*/
public static String scramble(String str)
{
Random rand=new Random();
int n=str.length();
int r;
StringBuilder s=new StringBuilder(str);
for(int i=1;i<n-1;i++)
{
r=Math.abs(rand.nextInt(n-2))+1;
s.setCharAt(i, str.charAt(r));
s.setCharAt(r, str.charAt(i));
str=s.toString();
}
return s.toString();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner src=new Scanner(System.in);
System.out.println("Enter any string:");
String s=src.next();
while(s.length()<6)
{
System.out.println("Enter a valid word");
s=src.next();
}
System.out.println(scramble(s));
}
}