University of Toronto - Fall 2000
Department of Computer Science
Week 8
- Loop Review Example
Replace.java
/**
* Replace: This program reads in lines of input until the user enters
* the word 'stop.' For each line of input, the program should print out
* the line after substituting each occurence of the letter 'e' (lower
* case only) with an A, then a B, then a C, then a D, etc. You can assume
* that each input line has no more than 26 occurences of the letter 'e'.
*/
import java.io.*;
public class Replace {
public static void main (String[] args) throws IOException {
BufferedReader in = new BufferedReader (new
InputStreamReader (System.in));
// Prompt user, and read in first line of text
System.out.println ("Enter lines of text. Use 'stop' to end.");
String line = in.readLine();
// Repeat until user enters 'stop'
while (!line.equals("stop")) {
String result = ""; // Stores the output line
int capCounter = 0; // Keeps track of how far we are away
// from capital 'A' in the ASCII table.
// Loop to count through each character in the original line.
for (int i=0; i<line.length(); i++) {
// The character was an 'e', so replace it the ASCII value
// of 'A' plus our 'capCounter' as described above. Cast
// the result back to character.
if (line.charAt(i) == 'e') {
result += (char)('A' + capCounter);
capCounter++;
} else {
result += line.charAt(i);
}
}
// Print out the new line.
System.out.println (result);
// Read next line of text.
line = in.readLine();
}
}
}
Sample program run (input boldfaced)
Enter lines of text. Use 'stop' to end.
kjsweaeasefasefaesfsefawfasefawefsfase
kjswAaBasCfasDfaEsfsFfawfasGfawHfsfasI
esjaslejafslekjfalsejflaskejalskejfalskelfkasealeee
AsjaslBjafslCkjfalsDjflaskEjalskFjfalskGlfkasHalIJK
awsekarjselakfjealksjelfaeseeeeeeeeeafasefasefasefawefseefase
awsAkarjsBlakfjCalksjDlfaEsFGHIJKLMNafasOfasPfasQfawRfsSTfasU
stop