When executing the code, to check whether the string is a palindrome, I get into the situation that with any correct determination of the inconsistency of the string to the palindrome conditions, I first receive the correct message that the string is not (it works inside the else in the function), and then it is an error that the string is (it works else in the body of the main program).
I understand that the case is somewhere in the final return, but what’s wrong, I can’t determine.
The task is given with the obligatory use of a logical recursive function without cycles, therefore, other implementation options, unfortunately, are not suitable.
It shows like this, for example: Enter the string: 1231 Unfortunately, the entered string is not a palindrome. We dance, we found a palindrome!
package com.company; import java.util.Scanner; public class Main { public static boolean palindrom(boolean prov, String str, int i, int len){ //если к середине строки мы не выпали по несовпадающим символам, значит нашли палиндром if (len - 1 <= i) { System.out.println("Танцуем, мы нашли палиндром!"); return prov = true; } //если символы по указателю счетчиков совпали, то уходим в рекурсию if (str.charAt(i) == str.charAt(len - 1)) palindrom(prov, str, i + 1, len - 1); //если не совпали, то строка не является палиндромом else { System.out.println("К большому сожалению, введенная строка не является палиндромом"); return prov = false; } return prov; } public static void main(String[] args) { //вводные System.out.println("Программа считывает строку и проверяет, является ли она палиндромом. Программа не чувствительна к регистру, но чувствительно к знакам пунктуации."); System.out.println(); //считываем строку, готовим переменные System.out.print("Введите строку: "); Scanner scan = new Scanner(System.in); String str = scan.nextLine(); str = str.replaceAll("\\s",""); str = str.toLowerCase(); int len = str.length(); int i = 0; boolean prov = true; //если строка пустая или содержит 1 символ, или функция вернула ложь, то не палиндром if (len <= 1 || palindrom(prov, str, i, len) == false) System.out.print("К большому сожалению, введенная строка не является палиндромом"); //иначе палиндром else System.out.println("Танцуем, мы нашли палиндром!"); } }