A
A
artem2020-12-07 22:09:50
Java
artem, 2020-12-07 22:09:50

Why does the search term take away the output result?

There is this little code:

if(newMatcher.find()) {
System.out.println("Введите текст в котором хотите совершить поиск : ");

        Scanner newScaner = new Scanner(System.in);
        String str = newScaner.nextLine();

        String text = new String(str);



        System.out.println("Теперь введите слово, которое хотите найти");

        Scanner newScaner2 = new Scanner(System.in);
        String str2 = newScaner.nextLine();

        Pattern newPattern = Pattern.compile(str2);
        Matcher newMatcher = newPattern.matcher(text);

        if(newMatcher.find()) {
            while(newMatcher.find()) {
                System.out.println(newMatcher.group());
            }
        }else {
            System.out.println("Нет совпадений!");
        }


Why, when there are 3 words in the text that the program should find and display, does it print one less?

This is facilitated by the wrapped while in the if. Why does this work? After all, without if, it displays all 3.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sergey, 2020-12-08
@arteqrt

because each call find()moves it from the current to the next match:
find the first, and then for each subsequent call to find() it will move to the next match.
therefore findfor while a is ifusually usedmatches()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question