Reputation: 33
I have an assignment where I need to display 200 random characters and then ask the use what letter they would like to replace and then replace all those letters. I have the random characters generated, but I am having trouble with replacing the letters. Can someone help lead me in the right direction? Here are some other questions i have:
Here is my code:
import java.io.*;
import java.util.Scanner;
public class Alphabet {
public static char getRandomCharacter(char ch1, char ch2) {
return (char) (ch1 + Math.random() * (ch2 - ch1 + 1));
}
public static char getRandomUpperCaseLetter() {
return getRandomCharacter('A', 'Z');
}
public static void main(String[] args) throws IOException {
try (RandomAccessFile raf = new RandomAccessFile("Alphabet.dat", "rw")) {
raf.setLength(0);
for (int row = 0; row < 10; ++row){
for (int col = 0; col < 10; ++col) {
raf.writeChar(getRandomUpperCaseLetter());
}
}
raf.seek(0);
for (int row = 0; row < 10; ++row){
for (int col = 0; col < 10; ++col) {
System.out.print(raf.readChar() +" ");
}
System.out.println();
}
Scanner Console = new Scanner(System.in);
System.out.println("Current length of file is: "
+ raf.length());
System.out.print("Replace Characters: ");
String letter = Console.next();
System.out.print("With Character: ");
String ch = Console.next();
for(int j = 0; j < raf.length(); ++j){
raf.seek((raf.length()-1)*2);
raf.writeChars(ch);
System.out.print("Position" + raf.getFilePointer());
}
raf.writeChars(ch);
raf.seek(0);
for (int row = 0; row < 10; ++row){
for (int col = 0; col < 10; ++col) {
}
System.out.println();
}
}
}
}
Upvotes: 3
Views: 5964
Reputation: 2310
Try replacing for-loop (j < raf.length) with a while loop with the following contents:
long currPointer = 0;
while(currPointer < raf.length()) {
long currPointer = raf.getFilePointer(); // save current cursor position
char currentChar = raf.readChar(); // read current char
if (currentChar == letter) { // if char equals that to be replaced
raf.seek(currPointer); // step cursor one step back
raf.writeChar(ch); // replace char
}
currPointer = raf.getFilePointer() // store the position of the cursor
}
EDIT: now the file is traversed character by character, as opposed to byte by byte. Given that various character encodings may not use a constant number of bytes per character, this is the easiest approach.
Basically:
LOOP through all characters in file
IF current character equals that to be replaced
step cursor back by one (otherwise you'd be overwriting the next character)
replace character
Just out of curiosity, what exactly are you trying to achieve with:
raf.seek((raf.length()-1)*2);
Upvotes: 1