我制作了一个程序,旨在运行文本文档(莎士比亚的李尔王)并将字母 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;
}
}