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:
- Do I use a for loop for the seek method so it will find all those letters?
- I also need to display the position each of the letters. Would I use filepointer and would I put that in a loop as well?
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();
}
}
}
}