使用Matcher在Java中的用户输入中查找单词或短语

问题描述

这是一个简单的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());   
    }
}

}

解决方法

好吧,您在按7后不会调用search(),而在按5时,请参见代码:

else if (choice == 5) {
    searching();
}

您应该考虑为代码使用开关盒以提高可读性。

int choice = scan.nextInt();

switch (choice)
case 1:
    counting();
    break;
case 2:
    bigLetters();
    break();
case 3:
    smallLetters();
    break;
case 4:
    backward(); 
    break;
case 5:
    searching();
    break;
default:
    System.exit(0);
}