Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Java Program: It is a well-known phenomenon that most people are easily

ID: 3733002 • Letter: W

Question

Write a Java Program:

It is a well-known phenomenon that most people are easily able to read a text whose words have two characters flipped, provided the first and last letter of each word are not changed. For example: I dn'ot gvie a dman for a man taht can olny sepll a wrod one way. (Mark Twain) Write a method String scramble( String word) that constructs a scrambled version of a given word, randomly flipping two characters other than the first and last one. Then write a program that reads words and prints the scrambled words. The following pseudocode may help you to develop the method Check if word length of string is greater than 3 If word length is greater than 3 Generate 2 indexes of the characters to swap Swap the characters in the string Return the string

Explanation / Answer

import java.util.Random;
class Main {
public static String scramble(String word)
{
int l = word.length();
int first, last;
  
// checking if the length is greater than 3
if(l > 3)
{
// generating 2 random numbers
Random randomNum = new Random();
first = 1 + randomNum.nextInt(l-2);
last = first;
while(first == last)
last = 1 + randomNum.nextInt(l-2);
  
// SWAPPING characters
char end = word.charAt(last);
word = word.substring(0,last) + word.charAt(first) + word.substring(last+1);
word = word.substring(0,first) + end + word.substring(first+1);
}
  
return word;
}
  
public static void main(String[] args) {
System.out.println(scramble("cheggindia"));
System.out.println(scramble("johnnash"));
System.out.println(scramble("jyo"));
}
}

/*OUTPUT
chegnigdia
johsnanh
jyo
*/