【发布时间】:2020-09-28 13:03:05
【问题描述】:
可以说是一个简单的 cmd 文本编辑器。用户粘贴他们想要编辑的文本,然后选择 7 个选项之一。其中之一 (7) 正在寻找特定的单词/短语。问题是,按 7 后程序停止执行,因此用户无法写出他们要查找的单词。控制台没有显示任何错误。
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 tect editor.\n"
+ "What do you wish to do?\n"
+ "1. Count characters.\n"
+ "2. Put text to upper case.\n"
+ "3. Put text to lower case.\n"
+ "4. Put text backwards.\n"
+ "5. not yet.\n"
+ "6. not yet.\n"
+ "7. Search in text.\n"
+ "8. Exit program.");
int choice = scan.nextInt();
if (choice == 1) {
counting();
}
else if (choice == 2) {
bigLetters();
}
else if (choice == 3) {
smallLetters();
}
else if (choice == 4) {
backward();
}
else if (choice == 5) {
searching();
}
else if (choice == 8) {
System.exit(0);
}
}
public void counting() {
System.out.println("Character count: " + text.length());
menu();
}
public void bigLetters() {
System.out.println(text.toUpperCase());
menu();
}
public void smallLetters() {
System.out.println(text.toLowerCase());
menu();
}
public void backward() {
String source = text;
for (String part : source.split(" ")) {
System.out.println(new StringBuilder(part).reverse().toString());
System.out.print(" ");
}
menu();
}
public void searching() {
String source = text;
String word = scan.nextLine();
System.out.println("What word or phrase do you wish to find?"); //Here the user writes a word or a phrase they want to find
scan.nextLine();
String patternString = word;
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(text);
while(matcher.find()) {
System.out.println(matcher.start() + matcher.end());
}
}
}
【问题讨论】:
-
您在
if else块中缺少选项 7。 -
6和7没有条件。 -
感谢您指出这一点,这是我犯的一个愚蠢的错误。
-
您应该添加一个额外的
else块,其中包含System.out.println("Invalid choice: "+choice);之类的内容。它不会解决您的问题,但会帮助您和您的用户更好地了解正在发生的事情。