Description: Typoglycemia refers to the apparent phenomenon that most people are
ID: 3566402 • Letter: D
Question
Description:
Typoglycemia refers to the apparent 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 dnot give a dman for a man that can olny sepll a word one way. (Mrak Taiwn)
Objective:
Write a program that reads words and prints scrambled words. To do this, first create a class named WordScramble. The class will not need any instance variables. Include in your class a method with signature public String scramble(String word) that constructs a scrambled version of a given word, randomly flipping two characters other than the first one and last one. Note that words with 1, 2, or 3 characters are not changed, so your method might test for those first.
Next, create a class named TestWordScramble that also has no instance variables, but has a main method that prompts a user to enter a sentence, prints the sentence unchanged, and then prints the sentence with the appropriate words scrambled.
Example Dialog:
Welcome to Word Scramble. Please enter a sentence without any punctuation.
This is my test of word scramble
You entered: This is my test of word scramble
Scrambled version: Tihs is my tset of wrod scmarble
Explanation / Answer
import java.util.Random;
import java.util.Scanner;
class WordScramble{
static int pos1,pos2,len;
static Random r = new Random();
static char temp;
static char[] tw;
public static String scramble(String word){
len = word.length();
tw = word.toCharArray();
if(len<3){
return word;
}
else{
pos1 = r.nextInt(len-3) + 1;
while(pos1 == (pos2 = r.nextInt(len-2) + 1)){}
temp = word.charAt(pos1);
tw[pos1] = word.charAt(pos2);
tw[pos2] = temp;
return new String(tw);
}
}
}
class TestWordScramble {
public static void main(String... args){
int i =0;
Scanner scr = new Scanner(System.in);
System.out.println("Welcome to Word Scramble. Please enter a sentence without any punctuation.");
String sentence = scr.nextLine();
String[] allWords = sentence.split(" ");
for(String eachWord : allWords){
allWords[i] = WordScramble.scramble(eachWord);
i++;
}
StringBuilder builder = new StringBuilder();
for(String s : allWords) {
builder.append(s + " ");
}
System.out.println("You Entered: " + sentence);
System.out.println("Scrambled Version: " + builder.toString());
}
}