JAVA Hi! So I\'m trying to make a program that uses a recursive method that dete
ID: 3666828 • Letter: J
Question
JAVA Hi! So I'm trying to make a program that uses a recursive method that determines if a string entered by the user is a palindrome. I thought it had something to do with lengthnum being defined in the recursive part but then I put it in a different method and it still doesn't work. Here's what I have, if you could please make changes on this so it works, or tell me what I'm doing wrong, thank you!!
import java.util.Scanner;
public class Palindromes {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
String Words = keyboard.nextLine();
int lengthnum = Words.length()-1;
int startnum = 0;
if (RecursionPart(Words, startnum, lengthnum) == true) {
System.out.println("palindrome");
} else {
System.out.println("not a palindrome");
}
}
public int RecursionPart( int lengthnum, String Words) {
lengthnum = Words.length()-1;
return lengthnum;
}
public static boolean RecursionPart(String Words, int startnum, int lengthnum) {
//lengthnum = Words.length()-1;
System.out.println((lengthnum));
if (Words.length() == 0 || Words.length() == 1 || Words.length() == 2) {
return true;
}
if (lengthnum== 0) {
return true;
}
else {
if (Words.charAt(startnum) != Words.charAt(lengthnum)) {
return false;
}
if (Words.charAt(startnum) == Words.charAt(lengthnum)) {
startnum++;
//lengthnum--;
return RecursionPart(Words, lengthnum, startnum);
}
}
return true;
}
}
Explanation / Answer
The problem is with the last part of the recursion function, see below :
public static boolean RecursionPart(String Words, int startnum, int lengthnum) {
//lengthnum = Words.length()-1;
System.out.println((lengthnum));
if (Words.length() == 0 || Words.length() == 1 || Words.length() == 2) {
return true;
}
if (lengthnum== 0) {
return true;
}
else {
if (Words.charAt(startnum) != Words.charAt(lengthnum)) {
return false;
}
if (Words.charAt(startnum) == Words.charAt(lengthnum)) {
startnum++;
lengthnum--; //------> this should not be comment, the length should decrease from the last
return RecursionPart(Words, lengthnum, startnum); //---> the position of lengthnum and startnum arguments are interchanged, it should actually be interchanged.
}
}
return true;
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
For a full working sample of your palindrome program, see below code :
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.