【发布时间】:2020-10-01 09:25:05
【问题描述】:
我正在制作一个必须使用 cmd 运行的文本编辑器。用户粘贴他们想要编辑的文本,然后他们选择他们想要用它做什么。我很难替换他们粘贴的部分文本。
这是我的编辑器代码(一部分):
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class TextEd {
public static void main(String[] args) {
Editor editor = new Editor();
editor.copiedText();
}
}
class Editor {
private Scanner scan = new Scanner(System.in);
private String text = " ";
public void copiedText() {
System.out.println("Paste your text here."); //The user input
text = scan.nextLine();
menu();
}
public void menu() {
System.out.println("Welcome to the text editor.\n"
+ "What do you wish to do?\n"
+ "1. Replace a word/line.\n"
+ "2. Exit program.");
int choice = scan.nextInt();
if (choice == 1) {
replacing();
}
else if (choice == 2) {
System.exit(0);
}
}
}
这里是替换部分的代码,我很纠结:
public void replacing() { //still not working argh
String replacement = scan.nextLine();
System.out.println("What dou you want to replace?");
try {
Pattern replacepat = Pattern.compile(scan.next());
Matcher match = replacepat.match(text);
System.out.println("What dou you want to replace it with?");
scan.nextLine();
boolean found = false;
while (match.find()) {
text = text.replaceAll(replacepat, replacement);
System.out.println(text);
}
}
catch (Exception e) {
System.out.println("There's been an error.");
}
}
我收到的错误通知我,Pattern 无法转换为 String - 我理解,replaceAll 可与 int 一起使用 - 但我不知道如何获取用户想要替换的文本的索引,因为用户的工作是粘贴文本,然后粘贴他们要替换的文本的另一部分。
【问题讨论】:
-
请发送minimal reproducible example,引用错误,提供示例输入和所需的输出/结果。