gpt4 book ai didi

java - 创建用 "sir"替换 "dawg"的方法?

转载 作者:行者123 更新时间:2023-12-02 05:19:48 26 4
gpt4 key购买 nike

我制作了一个程序,旨在运行文本文档(莎士比亚的《李尔王》),并将字母 s 的所有实例替换为 z,将“sir”替换为“dawg”。我可以使用第一种方法,但是我无法弄清楚我的其他方法(旨在替换“先生”)的问题所在。

一切看起来都不错,但它一直显示“超出范围”。我的代码中有任何建议/错误吗?

import java.util.Scanner;
import java.io.*;
public class KingLear
{
public static void main (String[] args) throws FileNotFoundException
{
PrintStream ps = new PrintStream("new_lear.txt");
Scanner fileScan = new Scanner(new File("king_lear.txt"));
Scanner fileScan2 = new Scanner(new File("king_lear.txt"));
String currentLine;
String currentLine2;

while (fileScan2.hasNextLine())
{
currentLine2 = fileScan.nextLine();

ps.println(dawg(currentLine2));
}


while (fileScan.hasNextLine())
{
currentLine = fileScan.nextLine();

ps.println(zReplace(currentLine));

}
}
public static String zReplace (String line)
{
String newLine = "";
for (int i = 0; i < line.length(); i++)
{
char letter = line.charAt(i+1);
if (letter == 's')
newLine += 'z';
else if (letter == 'S')
newLine += 'Z';
else
newLine += letter;
}
return newLine;
}

public static String dawg (String line)
{
String newLine = " ";
for (int i = 0; i < line.length(); i++)
{
char letter = line.charAt(i);
if (line.charAt(i) == 's' && line.charAt(i+1) == 'i' && line.charAt(i+2) == 'r')
{
newLine +="dawg";
}

}
return newLine;
}
}

最佳答案

无需重新发明轮子。只需使用 String.replace而不是让事情复杂化。

line = line.replace("sir", "dawg");

到目前为止,您拥有的所有替换逻辑都可以重写为:

line = line.replace("s", "z").replace("S", "Z").replace("sir", "dawg");

关于java - 创建用 "sir"替换 "dawg"的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26599368/

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