我有一个任务,需要显示200个随机字符,然后询问用户要替换哪个字母,并替换所有这些字母。我已经生成了随机字符,但在替换字符方面遇到了麻烦。有人能帮忙指导一下吗?以下是我还有的几个问题:
- 我是否需要使用for循环来查找所有这些字母的位置?
- 我还需要显示每个字母的位置。我是否应该使用filepointer?我是否也需要将它放在一个循环中?
以下是我的代码:
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();
}
}
}
}
while()
循环来完成这个任务。 - oakTree