In java language please!! It is a well-known phenomenon that most people are eas
ID: 3763195 • Letter: I
Question
In java language please!!
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 program with a method scramble(String word) that reads the contents of a file with a paragraph in it and constructs a scrambled version of the paragraph, randomly flipping two characters other than the first and last for all words greater than length 3.
Explanation / Answer
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* @author Srinivas
*
*/
public class ScrambleMain {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("paragraph.txt");
String scrambledString = "";
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String lineArr[] = line.split(" ");
System.out.println("input string :" + line);
for (int i = 0; i < lineArr.length; i++) {
String str = lineArr[i];
if (str.length() > 3) {
scrambledString += scramble(str) + " ";
} else {
scrambledString += str + " ";
}
}
}
System.out.println("scrambledString : " + scrambledString);
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static String scramble(String str) {
StringBuilder newStringBuilder = new StringBuilder();
char firstLetter = str.charAt(0);
char lastLetter = str.charAt(str.length() - 1);
StringBuilder stringBuilder = new StringBuilder(str.substring(1,
str.length() - 1));
while (stringBuilder.length() > 0) {
int n = (int) (Math.random() * stringBuilder.length());
newStringBuilder.append(stringBuilder.charAt(n));
stringBuilder.deleteCharAt(n);
}
return firstLetter + newStringBuilder.toString() + lastLetter;
}
}
pragraph.txt:
I don't give a damn for a man that can only spell a word one way
OUTPUT:
input string :I don't give a damn for a man that can only spell a word one way
scrambledString : I d'ont give a dman for a man that can olny splel a word one way
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.