In: Computer Science
Assignment Purpose
The purpose of this lab is to 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.
Java code:
/**scramble word
* It is quite interesting that most of us are likely to be able to
read and comprehend words,
* even if the alphabets of these words are scrambled (two of them)
given
* the fact that the first and last alphabets remain the same
*
*/
import java.util.Scanner;
public class ScrambleWord {
public String scramble(String word) // scramble method
definition
{
String result;
StringBuffer buffer = new
StringBuffer(word); // create stringbuffer object
if (word.length() >= 6) //
validate the word length greater than 6 or not
{
// get the word
length and subtract by 3 to avoid last character
int len =
word.length() - 3;
// generate
random number and add by 1 to avoid first character
int randomnumber
= (int) (Math.random() * len) + 1;
// generate
another random number to fetch another one character
int
randomnumber1 = randomnumber + 1;
// get the first
character to swap
String first =
word.substring(randomnumber, (randomnumber + 1));
// get the
second the chracter to swap
String second =
word.substring(randomnumber1, (randomnumber1 + 1));
// swap the
first character
buffer.setCharAt(randomnumber, second.charAt(0));
// swap the
second character
buffer.setCharAt(randomnumber1, first.charAt(0));
result = buffer.toString();
} else {
result = "enter
valid word";
}
return result;
}
public static void main(String args[]) {
ScrambleWord sw = new
ScrambleWord();
String word, scrambleword;
Scanner ss = new
Scanner(System.in);
System.out.println("Enter
word");
word = ss.next(); // get word from
the user
scrambleword = sw.scramble(word);
// call the scramble method
System.out.println(scrambleword);
// print the scramble word
}
}
Sample
outputs:
sample 1:
sample 2:
Note : Read comments for better understanding of the code.
Steps to generate java document ( I used eclipse IDE)
Step 1 − Open eclipse, select the option Project →Generate Javadoc.
Step 2 − Select the javadoc.exe file from the
bin folder of java installation directory,
select the destination folder for the generated java doc and select
Next.
Step 3 − Type the title of the documentation in
the Document title and select the
finish button.
Step 4 − Finally, you can observe the generated doc files in the generated folder.
You can view the document by opening the index.html file with the browser.