I'm working on an experiment to parse speech out of an emote in a text roleplaying game (MUD) so that if you can't hear it correctly, or if it's in a different language, you won't understand it. This works correctly, but I was just wanting to make sure it was as clear and efficient as possible.
import java.util.Scanner;
import java.util.Random;
public class EmoteParser {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an emote: ");
String emote = scanner.nextLine();
System.out.println("Original emote:\n" + emote);
System.out.println("\nParsed emote:\n" + jumbleEmoteSpeech(emote));
}
public static String jumbleEmoteSpeech(String emote) {
StringBuilder out = new StringBuilder();
int quote1Location = emote.indexOf('"');
if (quote1Location == -1) {
out.append(emote);
}
else {
int quote2Location;
int currentIndex = 0;
boolean found = true;
do {
quote2Location = emote.indexOf('"', quote1Location + 1);
if (quote2Location == -1 || quote2Location < currentIndex) {
out.append(emote.substring(currentIndex));
found = false;
}
else {
out.append(emote.substring(currentIndex, quote1Location + 1));
out.append(jumble(emote.substring(quote1Location + 1, quote2Location)));
currentIndex = quote2Location;
quote1Location = emote.indexOf('"', currentIndex + 1);
}
} while (found);
}
return out.toString();
}
public static String jumble(String text) {
StringBuilder out = new StringBuilder();
Random generator = new Random();
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if (Character.isLetter(ch)) {
if (Character.isUpperCase(ch)) {
out.append((char)('A' + generator.nextInt(26)));
}
else {
out.append((char)('a' + generator.nextInt(26)));
}
}
else if (Character.isDigit(ch)) {
out.append((char)('0' + generator.nextInt(10)));
}
else {
out.append(text.charAt(i));
}
}
return out.toString();
}
}
Also, is there any real benefit to using '"'
vs "\""
? I think '"'
is more readable, and any performance difference is probably optimized out anyway.