1. Getting Input from the User
Getting data from the user is a little tricky. Enter this code into a file named Eliza.java:
public class Eliza {
static String buffer;
static java.io.BufferedReader standardIn;
static String talkAboutPhrase = "talk about";
public static String replace(String buffer, String find, String replace) {
int findPos = buffer.indexOf(find);
if (findPos >=0 ) {
return buffer.substring(0, findPos) + replace +
buffer.substring(findPos + find.length());
} else {
return buffer;
}
}
public static void main(String args[]) {
standardIn = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
System.out.println("Hello, my name is Eliza. Tell me your problem.");
while (true) {
System.out.print("> ");
try {
buffer = standardIn.readLine();
} catch (java.io.IOException ioe) {
System.out.println("An IOException occurred.");
}
int talkAbout = buffer.indexOf(talkAboutPhrase);
if (talkAbout >= 0) {
String topic = buffer.substring(talkAbout + 1 + talkAboutPhrase.length());
topic = replace(topic, "my", "your");
System.out.println("Tell me more about " + topic);
} else {
buffer = replace(buffer, "I", "you");
buffer = replace(buffer, "me", "you");
System.out.println("Why do you say that " + buffer);
}
}
}
}
