gpt4 book ai didi

java - 寻找方法 RandomAccessFile

转载 作者:行者123 更新时间:2023-11-30 11:05:03 28 4
gpt4 key购买 nike

我有一个任务,我需要显示 200 个随机字符,然后询问使用他们想要替换的字母,然后替换所有这些字母。我生成了随机字符,但在替换字母时遇到了问题。有人可以帮助我朝着正确的方向前进吗?以下是我的一些其他问题:

  • 我是否对 seek 方法使用 for 循环以便它找到所有这些字母?
  • 我还需要显示每个字母的位置。我会使用文件指针吗?我会把它放在一个循环中吗?

这是我的代码:

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();
}
}
}
}

最佳答案

尝试将 for-loop (j < raf.length) 替换为具有以下内容的 while 循环:

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

}

编辑:现在文件是一个字符一个字符地遍历,而不是一个字节一个字节地遍历。考虑到各种字符编码可能不会为每个字符使用固定数量的字节,这是最简单的方法。

基本上:

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

出于好奇,你到底想用什么来实现:

raf.seek((raf.length()-1)*2);

关于java - 寻找方法 RandomAccessFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29781193/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com